【问题标题】:Twinx makes labels disappearTwinx 让标签消失
【发布时间】:2022-08-19 18:15:56
【问题描述】:

我在使用 twinx 函数时设置 x 标签时遇到问题。我的原始数据是一个pandas数据框,即df,它有3个属性,\"name\"=产品名称,\"sold\"=售出的商品数量,和\"revenue\"。名称是熊猫系列(如“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()

    标签: python pandas matplotlib plot label


    【解决方案1】:

    您需要使用 set_xticklabels() 设置 X 轴的标签以显示字段。绘制图形后添加这条线。

    ax.set_xticklabels(df.Name)
    

    你会得到下面的情节。

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 2011-12-08
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 2016-05-10
      相关资源
      最近更新 更多