不带反转轴值的反转条形图

Reverse order bar chart without reversing axis values

我正尝试在 excel 中以倒序类别创建条形图。

下面的技巧:

chart.set_y_axis({ 'reverse': True})

但是 x 轴值位于图表顶部,而我想将它们保留在底部。

我试图颠倒顺序然后通过以下方式移动 x 轴标签:

chart.set_x_axis({ 'label_position': 'low'})

这似乎没有做任何事情。这很奇怪,因为如果我不反转 y 轴而只是将 x 轴位置设置为“高”,那么它确实会将 x 轴值移动到顶部。所以我不知道为什么它会赢'也把它移到底部。

如何反转 excel 条形图中类别的顺序,同时将 x 轴值保持在底部?

示例代码:

import pandas as pd

# Some sample data to plot.
list_data = [10, 20, 30, 20, 15, 30, 45]

# Create a Pandas dataframe from the data.
df = pd.DataFrame(list_data)

# Create a Pandas Excel writer using XlsxWriter as the engine.
excel_file = 'column.xlsx'
sheet_name = 'Sheet1'

writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')
df.to_excel(writer, sheet_name=sheet_name)
workbook = writer.book
worksheet = writer.sheets[sheet_name]

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

# Reverse Order
chart.set_y_axis({ 'reverse': True,
                   'label_position': 'low'
                   })
# Try and fail to get x-axis values on bottom instead of top
chart.set_x_axis({ 'label_position': 'low'
                   })
# Configure the series of the chart from the dataframe data.
chart.add_series({
    'values':     '=Sheet1!$B:$B',
})

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

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

P.s。不确定这里是否允许这样的评论,但 xlsxwriter 是自切片面包以来最好的东西!

要在 Excel(和 XlsxWriter)中获得您想要的输出类型,您需要使用“轴在最大类别处交叉”选项设置轴的交叉点。

对于 XlsxWriter,您可以使用轴 crossing 参数来完成。像这样:

import pandas as pd

# Some sample data to plot.
list_data = [10, 20, 30, 20, 15, 30, 45]

# Create a Pandas dataframe from the data.
df = pd.DataFrame(list_data)

# Create a Pandas Excel writer using XlsxWriter as the engine.
excel_file = 'column.xlsx'
sheet_name = 'Sheet1'

writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')
df.to_excel(writer, sheet_name=sheet_name)
workbook = writer.book
worksheet = writer.sheets[sheet_name]

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

# Reverse Order
chart.set_y_axis({'reverse': True,
                  'crossing': 'max'})

# Configure the series of the chart from the dataframe data.
chart.add_series({'values': '=Sheet1!$B:$B'})

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

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

输出: