I automate some task with openpyxl with xlsx file, i created a piechart but i want the piechart to show the labels and not only the value ( got exemple apple, cherry… will be in text inside the pie is there a way to do that with openpyxl ?
Thanks
from openpyxl import Workbook
from openpyxl.chart import (
PieChart,
ProjectedPieChart,
Reference
)
from openpyxl.chart.series import DataPoint
data = [
['Pie', 'Sold'],
['Apple', 50],
['Cherry', 30],
['Pumpkin', 10],
['Chocolate', 40],
]
wb = Workbook()
ws = wb.active
for row in data:
ws.append(row)
pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
pie.title = "Pies sold by category"
Do you want to do something like this where name and percent is marked on the segments?
from openpyxl import Workbook
from openpyxl.chart.label import DataLabelList
from openpyxl.chart import (
PieChart,
Reference
)
data = [
['Pie', 'Sold'],
['Apple', 50],
['Cherry', 30],
['Pumpkin', 10],
['Chocolate', 40],
]
wb = Workbook()
ws = wb.active
for row in data:
ws.append(row)
pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
pie.title = "Pies sold by category"
### Add Label into chart
pie.dataLabels = DataLabelList()
pie.dataLabels.showPercent = True
pie.dataLabels.showCatName = True
ws.add_chart(pie, "A10")
wb.save('test_chart.xlsx')
It should produce a chart like
Related
I want to group the x_axis (Date) so that if there is a cell with 01/01/2022 & another 01/01/2022 it will only show one bar with 01/01/2022, here it actualy print each row with a bar
How can i do that in openpyxl please
Thanks in advance
from openpyxl import Workbook
from openpyxl.chart import BarChart, Series, Reference
wb = Workbook(write_only=True)
ws = wb.create_sheet()
rows = [
('Date', 'Batch 1'),
(01/01/2022, 10),
(01/01/2022, 40),
(02/01/2022, 50),
(04/01/2022, 20)
]
for row in rows:
ws.append(row)
chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.title = "Bar Chart"
chart1.y_axis.title = 'Test number'
chart1.x_axis.title = 'Sample length (mm)'
data = Reference(ws, min_col=2, min_row=1, max_row=5, max_col=2)
cats = Reference(ws, min_col=1, min_row=2, max_row=5)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")
So you want a stacked chart like this then?
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
rows = [
('Date', 'Batch 1', 'Batch 2'),
('01/01/2022', 10, 40),
('02/01/2022', 50, ''),
('04/01/2022', 20, '')
]
wb = Workbook(write_only=True)
ws = wb.create_sheet()
for row in rows:
ws.append(row)
chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.title = "Bar Chart"
chart1.grouping = "stacked" # Stacked column chart
chart1.overlap = 100 # Set overlap to 100% so top column sits squarely on the bottom column
chart1.y_axis.title = 'Test number'
chart1.x_axis.title = 'Sample length (mm)'
data = Reference(ws, min_col=2, min_row=1, max_row=4, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=4)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")
wb.save('new_chart1.xlsx')
I have some data that is already in an xlsx sheet. Is it possible to build a chart using openpyxl with this data that already exists in these cells? The data gets updated monthly.
data
category 3/1/2021 3/8/2021
computer 2646 3000
network 117 200
other 316 20
total 3079 3220
Desired:
A chart month by month chart next to the data
Doing:
from datetime import date
from openpyxl import Workbook
from openpyxl.chart import (
LineChart,
Reference,
)
from openpyxl.chart.axis import DateAxis
wb = Workbook()
ws = wb.active
c2 = LineChart()
c2.title = "Date Axis"
c2.style = 12
c2.y_axis.title = "Size"
c2.y_axis.crossAx = 500
c2.x_axis = DateAxis(crossAx=100)
c2.x_axis.number_format = 'd-mmm'
c2.x_axis.majorTimeUnit = "days"
c2.x_axis.title = "Date"
c2.add_data(data, titles_from_data=True)
dates = Reference(ws, min_col=1, min_row=2, max_row=5)
c2.set_categories(dates)
ws.add_chart(c2, "E1")
Any suggestion is appreciated
#pull in your data
wb_obj = load_workbook(path)
sheet_obj = wb_obj.active
c1 = BarChart()
c1.title = "Test"
c1.y_axis.title = "Test1"
c1.x_axis.title = "Test2"
#reference your data
data = Reference(sheet_obj, min_col=2, min_row=2, max_col=3, max_row=5)
c1.add_data(data, titles_from_data=True)
#save the data
sheet_obj.add_chart(c1, "E1")
wb_obj.save("samples.xlsx")
I am trying add the Data into the existing Line Chart dynamically when new data comes in into the excel using openpyxl. Below is the sample code I tried But when else part is encountered there is no changes in the chart.
Thanks
from openpyxl import load_workbook
from openpyxl.chart import (LineChart, Reference)
wb = load_workbook("Hello.xlsx")
sheet = wb.active
exists = 0
chart = LineChart()
if exists == 1:
values = Reference(sheet, min_col=3, min_row=1, max_row=sheet.max_row)
categories = Reference(sheet, min_col=1, min_row=2, max_row=sheet.max_row,max_col=1)
chart.add_data(values, titles_from_data=True)
chart.set_categories(categories)
chart.title = "sample"
chart.x_axis.title = "date"
chart.y_axis.title = "followers"
sheet.add_chart(chart, "F2")
else:
values_update = Reference(sheet, min_col=3, min_row=1, max_row=sheet.max_row)
chart.add_data(values_update)
wb.save("Hello.xlsx")
When I run my code it works very well and makes an excel file I named exel.xlsx, but there is no information in exel.xlsx.
I think I make a mistake in making a list but I can't find a solution.
def randStr(length=7):
characters = list('bcdghijkmnpqrtuvwxyz23456789')
shuffle(characters)
exel = ''.join(characters[:length])
listb = [exel]
listb.append(exel)
workbook = xlsxwriter.Workbook('Exel.xlsx')
worksheet = workbook.add_worksheet('randomise')
chart = workbook.add_chart({'type': 'line'})
expenses = (listb)
row = 0
col = 0
workbook.close()
return exel
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_line.xlsx')
worksheet = workbook.add_worksheet()
# Add the worksheet data to be plotted.
data = [10, 40, 50, 20, 10, 50]
worksheet.write_column('A1', data)
# Create a new chart object.
chart = workbook.add_chart({'type': 'line'})
# Add a series to the chart.
chart.add_series({'values': '=Sheet1!$A$1:$A$6'})
# Insert the chart into the worksheet.
worksheet.insert_chart('C1', chart)
workbook.close()
This is the basic way to add_chart , then adding the values to chart and inserting the chart .
But you are not adding any value to your chart. Moreover you are not adding any value to the column/row in sheet.
I ran your code , sheet with name "randomise" is created , but no data in it, as you havent added anything
solved!
def randStr(length=7):
characters = list('bcdghijkmnpqrtuvwxyz23456789')
shuffle(characters)
listc=''.join(characters[:length])
return listc
listb=[]
if __name__ == '__main__':
for i in range(20):
value1=(randStr())
listb.append(value1)
workbook = xlsxwriter.Workbook('Exel.xlsx')
worksheet = workbook.add_worksheet('randomise')
worksheet.write_column(0,0,listb)
chart = workbook.add_chart({'type': 'line'})
expenses =(listb)
row = 0
col = 0
workbook.close()
img = makeImage(value1, width=512)
with open('%d.png' % i, 'wb') as f:
f.write(img)
print (i)
I bet I'm really close here. I'm trying to look at spreadsheets with potentially 100's of columns and create a plot in a new spreadsheet for each column on the fly. I've got a few of these working where I simply call multiple calls to chart1,chart2,chart3......
What I have below loops fine, inserts the data in the first sheet, creates the second sheet and inserts only the first chart. How do I write the loop to create "n" charts?
I bet it's a silly trivial thing.
Thanks in advance.
Input Data:
https://drive.google.com/open?id=1sts5axnT7aQ04zHv8nPwhnrQPDb7oZlV
import pandas as pd
import codecs
import csv
import os
import xlsxwriter
import datetime
df3 = pd.read_csv('TEST.csv', index_col=0, header=[0], low_memory=False, na_filter=True, encoding='utf-8')
writer2 = pd.ExcelWriter('TEST.xlsx', engine='xlsxwriter')
#define the sheetname
stage = 10
sheetname1 = "Stage_" +str(stage)
print(sheetname1)
df3.to_excel(writer2, sheet_name = sheetname1 , startrow=4, startcol=0, encoding='utf8')
maxcol = df3.shape[1]-1
maxlen = df3.shape[0]-1
print(maxcol, maxlen)
#set the workbook value
c = df3[['TWO']]
workbook = writer2.book
#set the worksheet value
sheetname2 = "Stage_" +str(stage) +str("_P")
c.to_excel(writer2, sheet_name = sheetname2 , startrow=4, startcol=0, encoding='utf8')
print(sheetname2)
worksheet = writer2.sheets[ sheetname2 ]
for i in range(2, maxcol):
TITLE = df3.columns[i]
LOC_NUM = (i - 1) * 34 - 33
LOCATION = "C" +str(LOC_NUM)
print("TITLE:", TITLE, "GRAPH_LOCATION:", LOC_NUM,LOCATION, "LENGTH:", maxlen, "INDICE:", i)
chart = workbook.add_chart({'type': 'line'})
chart.set_size({'width': 1200, 'height': 640})
chart.add_series({"values" : [ sheetname1 , 7, i ,maxlen, i ],"name" : TITLE })
chart.set_x_axis({'name': 'Time (s)', 'position_axis': 'on_tick'})
chart.set_y_axis({'name': 'Test', 'major_gridlines': {'visible': False}})
# Turn off chart legend. It is on by default in Excel.
chart.set_legend({'position': 'none'})
worksheet.insert_chart( LOCATION , chart )
writer2.save()