Namak
Namak

Reputation: 29

Not getting category names in excel graph using Xlsxwriter in Python

I have a table like

A   | B
Foo | 150
Baz | 209
Bar | 123

I am using a script

workbook  = writer.book
worksheet = writer.sheets['Foo']

chart = workbook.add_chart({'type': 'bar'})
chart.add_series({ 
    'categories': '= Foo!$A$2:$A$4',
    'values':     '=Foo!$B$2:$B$4'})

But, on the y-axis, I am not seeing "Foo", "Baz", and "Bar" categories names on the axis. How to resolve this?

Upvotes: 1

Views: 385

Answers (1)

jmcnamara
jmcnamara

Reputation: 41644

You have an additional space in the categories range '= Foo!$A$2:$A$4'. If you fix that it should work:

import pandas as pd


df = pd.DataFrame({'A': ['Foo', 'Baz', 'Bar'], 
                   'B': [150, 209, 123]})

writer = pd.ExcelWriter('pandas_chart.xlsx', engine='xlsxwriter')

df.to_excel(writer, sheet_name='Foo', index=False)

workbook  = writer.book
worksheet = writer.sheets['Foo']

# Create a chart object.
chart = workbook.add_chart({'type': 'bar'})

# Configure the series of the chart from the dataframe data.
chart.add_series({'categories': '=Foo!$A$2:$A$4',
                  'values':     '=Foo!$B$2:$B$4'})

# Insert the chart into the worksheet.
worksheet.insert_chart('D2', chart)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Output:

enter image description here

Upvotes: 1

Related Questions