在使用twinx函数时,设置x标签有问题。我的原始数据是熊猫的数据,即df,它有三个属性,“name”=产品名,“sold”=出售物品的数量,以及“收益”。它的名字是熊猫系列(比如"2洗发水“),但我不能把它设置为x滴答标签(见下图)。如何设置x标签以显示产品名称?
fig = plt.figure() # Create matplotlib figure
ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.
width = 0.4
df.sold.plot(kind='bar', color='red', ax=ax, width=width, position=1, rot=90)
df.revenue.plot(kind='bar', color='blue', ax=ax2, width=width, position=0, rot=90)
# print(type(df['name']), "\n", df['name'])
ax.set_ylabel('Sold')
ax2.set_ylabel('Revenue')
ax.legend(['Sold'], loc='upper left')
ax2.legend(['Revenue'], loc='upper right')
plt.show()

发布于 2022-08-19 10:15:56
您需要使用set_xticklabels()来设置X轴的标签以显示字段。在绘制图形后添加这一行。
ax.set_xticklabels(df.Name)你会得到下面的情节。

https://stackoverflow.com/questions/73414522
复制相似问题