使用secondary_y时Pandas图的自定义xlabel旋转问题

7gs2gvoe  于 2023-03-11  发布在  其他
关注(0)|答案(2)|浏览(183)

我想显示旋转45度的x标签。我厌倦了下面的代码,但它仍然显示旋转0度的x标签。
如何旋转标签?

df_final = pd.DataFrame({'Count':[8601,188497,808,7081,684,15601,75,12325],
                         'Average': [0.128,0.131,0.144,.184,.134,.152,0.139,0.127]})
width = 0.8
df_final['Count'].plot(kind='bar', width = width)
df_final['Average'].plot(secondary_y=True)
ax = plt.gca()
ax.set_xticklabels(['One', 'Two', 'Three', 'Four', 'Five','Six','Seven','Eight'],rotation = 45)
plt.show()
0sgqnhkj

0sgqnhkj1#

  • pandas.DataFrame.plot返回matplotlib.axes.Axes。因此,将第一个图的Axes赋给变量ax
    *ax = plt.gca()不是必需的,但如果使用df_final['Average'].plot(...),则直接位于df_final['Average'].plot(...)之前。
  • 第二个图的设置优先,因此旋转应在第二个图调用中设置为rot=45,或在set_xticklabels中设置。
  • 另请参见Add label values to bar chart and line chart以添加标签。
    *python 3.11pandas 1.5.3matplotlib 3.7.0中进行测试

样品数据和设置

import pandas as pd

df_final = pd.DataFrame({'Count': [8601, 188497, 808, 7081, 684, 15601, 75, 12325],
                         'Average': [0.128, 0.131, 0.144, 0.184, 0.134, 0.152, 0.139, 0.127]})

width = 0.8

labels = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']

选项1

# assign the plot to ax
ax = df_final['Count'].plot(kind='bar', width=width, figsize=(9, 6), legend=True)

# place the secondary plot on ax
df_final['Average'].plot(secondary_y=True, ax=ax, color='r', legend=True)  # optionally add rot=45 here

# set the custom xtick labels and rotate
_ = ax.set_xticklabels(labels, rotation=45)  # remove rotation=45 if using rot=45 in the previous line

选项2

# set the index values to the labels, providing the order corresponds to the DataFrame
df_final.index = labels

# initial plot
ax = df_final['Count'].plot(kind='bar', width=width, figsize=(9, 6), legend=True)

# secondary plot and specify rotation
df_final['Average'].plot(secondary_y=True, ax=ax, rot=45, color='r', legend=True)

选项3

  • 使用index参数创建具有自定义索引的DataFrame,然后像Option 2一样绘制,但不使用df_final.index = labels
df_final = pd.DataFrame({'Count': [8601, 188497, 808, 7081, 684, 15601, 75, 12325],
                         'Average': [0.128, 0.131, 0.144, 0.184, 0.134, 0.152, 0.139, 0.127]},
                        index=labels)

mrfwxfqh

mrfwxfqh2#

只需更改ax = plt.gca()的位置,您可以尝试以下代码:

df_final = pd.DataFrame({'Count':[8601,188497,808,7081,684,15601,75,12325],
                         'Average': [0.128,0.131,0.144,.184,.134,.152,0.139,0.127]})
width = 0.8
ax = plt.gca()
df_final['Count'].plot(kind='bar', width = width)
df_final['Average'].plot(secondary_y=True)
ax.set_xticklabels(['One', 'Two', 'Three', 'Four', 'Five','Six','Seven','Eight'],rotation = 45)
plt.show()

相关问题