Creating pie chart in python

隐身守侯 提交于 2021-02-10 12:13:25

问题


I have created my pie chart but right now I am using a range of cells like this:

chart3.add_series({
    'name': 'Pie data',
    'categories': '=Pivots!$A$3:$A$10',
    'values':     '=Pivots!$F$3:$F$10'})

which gives me a pie chart with the categories that are found in A3-A10 and values that correspond from cells F3-F10. The problem I am having is unfortunately I am not always going to have data in each of these cells. so I may have data in one worksheet that has categories and values that may range from A3-A6 and values = F3-F6 and sometimes it only has data that ranges from A3-A9 and values = F3-F9. My problem is when I show my legend for the different worksheets they have missing fields and I was wondering if their was a way to just get the length of A to get the categories and the length of F3 to get the values so when my legend is showing it shows and represents only the rows with data.


回答1:


Assuming that it's an option for you to dynamically hide the rows without data, then there's a fairly straightforward solution.

I reworked some sample data that are used in the xlsxwriter docs and then looked for any Nan values. If there are any then those are hidden and thus not in the pie chart.

import xlsxwriter
import pandas as pd

headings = ['Category', 'Values']
data = [
['Apple', 30],['Cherry', 20],['Pecan',15],['Blueberry', 10],['Pumpkin', 10],
['Mince', float('nan')],['Custard', 3],['Potato', 2],
]


pies = pd.DataFrame(data, columns = headings)

nan_rows = pies.loc[pies['Values'].isnull()].index.values
hide_rows = nan_rows + 2

workbook = xlsxwriter.Workbook('test.xlsx', {'strings_to_numbers':  True,
                                             'strings_to_formulas': True,
                                             'nan_inf_to_errors': True})

ws = workbook.add_worksheet('Pivots')

ws.write('A2', headings[0])
ws.write('F2', headings[1])
ws.write_column('A3', pies['Category'])
ws.write_column('F3', pies['Values'])


chart3 = workbook.add_chart({'type': 'pie'})

chart3.add_series({
'name': 'Pie data',
'categories': '=Pivots!$A$3:$A$10',
'values':     '=Pivots!$F$3:$F$10'})

chart3.set_title({'name': 'Popular Pie Types'})

chart3.set_style(10)
ws.insert_chart('G11', chart3, {'x_offset': 25, 'y_offset': 10})

#This is where we hide the rows in list called hide_rows
for row_position in hide_rows:
    ws.set_row(row_position, None, None, {'hidden': True})

workbook.close()



来源:https://stackoverflow.com/questions/46227040/creating-pie-chart-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!