i used this example to get started with pandas:
http://pandas-xlsxwriter-charts.readthedocs.io/chart_grouped_column.html#chart-grouped-column
i also want to save the chart in excel just like in the example
i would like to know how e.g. in the example above i can add a description or a table under the graph chart
the only thing related i found was this :
Add graph description under graph in pylab
but this is done with pylab, is the same possible with pandas and an excel chart?
In Excel you could add a text box and insert some text but that isn't possible with XlsxWriter.
You could use the chart title property but in Excel the title is generally at the top and not the bottom.
You can reposition it, manually, in Excel. This is also possible with XlsxWriter using the layout options of the different chart objects.
Here is an example:
import xlsxwriter
workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()
# Create a new Chart object.
chart = workbook.add_chart({'type': 'column'})
# Write some data to add to plot on the chart.
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
# Configure the charts. In simplest case we just add some data series.
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_series({'values': '=Sheet1!$C$1:$C$5'})
chart.set_x_axis({'name': 'X axis title'})
chart.set_y_axis({'name': 'Y axis title'})
chart.set_title({
'name': 'Here is some text to describe the chart',
'name_font': {'bold': False, 'size': 10},
'layout': {
'x': 0.25,
'y': 0.90,
}
})
chart.set_plotarea({
'layout': {
'x': 0.11,
'y': 0.10,
'width': 0.75,
'height': 0.60,
}
})
#Insert the chart into the worksheet.
worksheet.insert_chart('A7', chart)
workbook.close()
Note, you will need to do some trial and error with the layout property to get the layout that you want.
Output:
Related
I am using XlsxWriter to do create column charts with the y axis name showing horizontally at the top of the axis. The default orientation for the y axis name seems to be vertical, reading from bottom to top.
So I'm using the name font rotation to try to position it horizontally, reading from left to right. It all works fine for any rotation angle from -90 to 90, except for 0 (zero), which should be the horizontal orientation. It seems that when rotation is set to 0 (zero) it is simply disregarded and the name is shown vertically.
The workaround that achieves a visuaaly acceptable result is setting rotation to 1, or -1. This works for short names, but for longer names it starts to be noticeable that the text is not at 0 (zero) degrees - horizontal.
I am using Python version Python 3.8.3, xlsxwriter version 1.2.9, and Excel 365.
Here is some code that demonstrates the problem:
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.set_title({'name': 'Some Title',
'name_font': {'rotation': 0}})
chart.set_y_axis({'visible': False,
'name': 'Y Axis',
'name_font': {'size': 14, 'bold': False, 'italic': True, 'rotation': 0},
'name_layout': {'x': 0.025, 'y': 0.075}})
worksheet.insert_chart('E1', chart)
workbook.close()
Any ideas on how to show the y axis name horizontally?
That unfortunately is due to a small bug. I've fixed it in XlsxWriter release 1.4.0.
With the fix in place the output from your (nicely detailed) program is as expected:
For this question, I was provided the following information.
Data in code form:
order_data = {'Alice': {5: 'chocolate'},
'Bob': {9: 'vanilla'},
'Clair': {7: 'strawberry'},
'Drake': {10: 'chocolate' },
'Emma': {82: 'vanilla'},
'Alice': {70: 'strawberry'},
'Emma': {42: 'chocolate'},
'Ginger': {64: 'strawberry'} }
I was asked to make a bar graph detailing this data. The bar graph and the code used to make it using Altair is provided below.
import altair
data = altair.Data(customer=['Alice', 'Bob', 'Claire', 'Drake', 'Emma','Alice', 'Emma', 'Ginger'],
cakes=[5,9,7,10,82,70,42,64],
flavor=['chocolate', 'vanilla', 'strawberry','chocolate','vanilla','strawberry','chocolate','strawberry'])
chart = altair.Chart(data)
mark = chart.mark_bar()
enc = mark.encode(x='customer:N',y='cakes',color='flavor:N')
enc.display()
Graph:
My question is: What is the best way to go about constructing this graph using matplotlib?
I know this isn't an unusual graph per say but it is unusual in the sense that I have not found any replications of this kind of graph. Thank you!
It has already been answered, but you can also graph it in pandas.plot.
import pandas as pd
data = pd.DataFrame({'customer':['Alice', 'Bob', 'Claire', 'Drake', 'Emma','Alice', 'Emma', 'Ginger'],
'cakes':[5,9,7,10,82,70,42,64],
'flavor':['chocolate', 'vanilla', 'strawberry','chocolate','vanilla','strawberry','chocolate','strawberry']})
df = pd.DataFrame(data)
df = df.pivot(index='customer',columns='flavor', values='cakes').fillna(0)
df.plot(kind='bar', stacked=True)
Here is a reproduction of the Altair graph with Matplotlib. Note that I had to modify the order_data dictionary because a dict cannot be defined with multiple keys at once (so I had to group the dictionary by key values). Also note that some optionally styling statements are included to also mimic the style of Altair.
The trick is to use the bottom keyword argument of the ax.bar function. The following image is obtained from the code below.
import matplotlib.pyplot as plt
# data
order_data = {
"Alice": {"chocolate": 5, "strawberry": 70},
"Bob": {"vanilla": 9},
"Clair": {"strawberry": 7},
"Drake": {"chocolate": 10},
"Emma": {"chocolate": 42, "vanilla": 82},
"Ginger": {"strawberry": 64},
}
# init figure
fig, ax = plt.subplots(1, figsize=(2.5, 4))
colors = {"chocolate": "C0", "strawberry": "C1", "vanilla": "C2"}
# show a bar for each person
for person_id, (name, orders) in enumerate(order_data.items()):
quantities = 0
for order_id, (order, quantity) in enumerate(orders.items()):
ax.bar(person_id, quantity, bottom=quantities, color=colors[order])
quantities += quantity
# add legend
ax.legend([color for color in colors], bbox_to_anchor=(2.0, 1.0))
# remove top/right axes for style match
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.grid(axis="y", zorder=-1)
# ticks
ax.set_xticks(range(len(order_data)))
ax.set_xticklabels([name for name in order_data], rotation="vertical")
I am generating excel files with XlxsWriter that include some charts. I would like to save the resulting charts separately as images so I can attach them to an email (as a preview of the Excel file I'm sending). I'm able to create the Excel with charts, I just can't find any way to save the charts as an image in the XlxsWriter documentation.
I am doing this on a Mac, so unfortunately the solution using win32 doesn't help. excel2img looked promising, but also depends on win32.
Example chart generation is as follows (borrowed from the documentation). It generates a simple Excel file with a chart. I would like a png/jpg export of the chart from this Excel.
import xlsxwriter
workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()
# Create a new Chart object.
chart = workbook.add_chart({'type': 'column'})
# Write some data to add to plot on the chart.
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
# Configure the chart. In simplest case we add one or more data series.
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_series({'values': '=Sheet1!$C$1:$C$5'})
# Insert the chart into the worksheet.
worksheet.insert_chart('A7', chart)
# TODO How can I get the chart as a png/jpg
workbook.close()
I'm trying to generate simple pie chart for better visualization of some data, but XlsxWriter wont write data to two columns simultaneously. Where as other example is working fine.
I'm clueless where I might be going wrong
Following is the data :
{'core2': [10.3], 'core3': [4.17], 'core0': [58.68], 'core1': [24.42], 'core6': [0.02], 'core7': [0.0], 'core4': [2.31], 'core5': [0.12]})
Actual data is passed as list -> [10.3, 4.17, 58.68, 24.42, 0.02, 0.0, 2.31, 0.12] to below function
Please find below code :
def draw_simultaneously_busy_cores(type_of_chart,data,workbook):
print data
worksheet = workbook.add_worksheet()#'simultaneously_busy_cores')
bold = workbook.add_format({'bold': 1})
headings = [0, 1, 2, 3, 4, 5, 6, 7]
worksheet.write_column('$A$1', headings, bold)
worksheet.write_column('$B$1',headings)
chart1 = workbook.add_chart({'type': type_of_chart})
chart1.add_series({
'name': 'Simultaneous Busy Cores',
'categories': ['simultaneously_busy_cores', '=simultaneously_busy_cores!$A$1:$A$8'],
'values': ['simultaneously_busy_cores', '=simultaneously_busy_cores!$B$1:$B$8'],
#'data_labels': {'percentage': True, }
})
#Add a title.
chart1.set_title({'name': 'Simultaneous Busy Cores'})
#Set an Excel chart style. Colors with white outline and shadow.
chart1.set_style(10)
#Insert the chart into the worksheet (with an offset).
worksheet.insert_chart('C2', chart1, {'x_offset': 25, 'y_offset': 10})
thanks in advance. Image shows the outpput :
It should work. Here is an example with sample data:
import xlsxwriter
def draw_simultaneously_busy_cores(type_of_chart, data, workbook):
worksheet = workbook.add_worksheet('simultaneously_busy_cores')
bold = workbook.add_format({'bold': 1})
worksheet.write_column('A1', data, bold)
worksheet.write_column('B1', data)
chart1 = workbook.add_chart({'type': type_of_chart})
chart1.add_series({
'name': 'Simultaneous Busy Cores',
'categories': '=simultaneously_busy_cores!$A$1:$A$8',
'values': '=simultaneously_busy_cores!$B$1:$B$8',
})
#Add a title.
chart1.set_title({'name': 'Simultaneous Busy Cores'})
#Set an Excel chart style. Colors with white outline and shadow.
chart1.set_style(10)
#Insert the chart into the worksheet (with an offset).
worksheet.insert_chart('C2', chart1, {'x_offset': 25, 'y_offset': 10})
workbook = xlsxwriter.Workbook('test.xlsx')
data = [0, 1, 2, 3, 4, 5, 6, 7]
draw_simultaneously_busy_cores('line', data, workbook)
workbook.close()
Output:
The chart categories and values syntax in your example is incorrect. You are mixing the list and string syntaxes. Read through the documentation and examples again.
I have a plot that needs names as the values for the x-axis. I imagine this is accomplished via the set_x_axis function for chart objects but can't find the proper key in the documentation (http://xlsxwriter.readthedocs.io/chart.html#set_x_axis). The following code produces the graph below:
chart = workbook.add_chart({'type':'scatter'})
colLetter = alphabet[1] #alphabet is list of alphabet
for ii in range(4):
colLetter = alphabet[ii+1]
chart.add_series({
'name': '=Sheet1!$%s$1'%colLetter,
'categories': '=Sheet1!$A$2:$A$'+str(lastRowNumber),
'values': '=Sheet1!$%s$2:$%s$6'%(colLetter, colLetter),
})
chart.set_title({'name': 'Cityblock'})
chart.set_x_axis({'name': 'Subject'})
chart.set_y_axis({'name': 'Distance'})
chart.set_style(11)
worksheet.insert_chart('F1', chart)
Any suggestions? I'm using xlsxwriter with python 2.7.
Just set the series categories to point to the strings, or numbers, or dates that you wish to plot.
For example:
import xlsxwriter
workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()
# Add a column chart.
chart = workbook.add_chart({'type': 'column'})
# Write some data to add to plot on the chart.
worksheet.write_column('A1', ['Bob', 'Eve', 'Ann'])
worksheet.write_column('B1', [5, 10, 7])
# Configure the chart.
chart.add_series({'categories': '=Sheet1!$A$1:$A$3',
'values': '=Sheet1!$B$1:$B$3'})
# Insert the chart into the worksheet.
worksheet.insert_chart('D1', chart)
workbook.close()
Output: