【问题标题】:Pandas Bar Plot and Labels in SubplotsPandas 条形图和子图中的标签
【发布时间】:2018-11-28 21:33:28
【问题描述】:
df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
x=[1,2,3,4,5]
y=[1,4,9,16,25]

fig, axes = plt.subplots(figsize=(8,8),nrows=2, ncols=2)
ax1=plt.subplot(2,2,1)
plt.plot(x,y)

#ax2=plt.subplot(2,2,2)
df["b"].plot(ax=axes[0,1], kind='bar', grid=True)
df["c"].plot(ax=axes[1,0], kind='bar', grid=True)
df["d"].plot(ax=axes[1,1], kind='bar', grid=True)

ax1.grid(True)
ax1.set_ylabel('Test')
ax1.set_xlabel('Test2')

#ax2.set_ylabel('Test')

如何在我的子图中为条形图添加轴标签?请注意,我在测试时已注释掉 ax2=plt.subplot(2,2,2) 但这会完全擦除条形图并添加标签。为什么它会这样做,我该如何解决这个问题?下面是带有 ax2... 未注释的输出。

【问题讨论】:

    标签: pandas axis-labels subplot axes


    【解决方案1】:

    据我了解,您不需要ax1ax2。你最好使用轴网格:

    fig, axes = plt.subplots(figsize=(8,8),nrows=2, ncols=2)
    axes[0,0].plot(x,y)
    df["b"].plot(ax=axes[0,1], kind='bar', grid=True)
    df["c"].plot(ax=axes[1,0], kind='bar', grid=True)
    df["d"].plot(ax=axes[1,1], kind='bar', grid=True)
    axes[0,0].grid(True)
    axes[0,0].set_ylabel('Test')
    axes[0,0].set_xlabel('Test2')
    axes[0,1].set_ylabel('Test')
    

    输出:

    【讨论】:

    • 您可以考虑在代码末尾添加plt.tight_layout()
    • @user32185,就情节而言,我没有看到相当大的重叠。但可以肯定的是,添加 plt.tight_layout() 不会影响 OP 的原始问题。谢谢。
    • y_labelaxes[0,1] 的情节太接近与axes[0,0] 恕我直言的情节的框。无论如何,我们的答案是完美的,应该被接受。
    • @user32185 你是绝对正确的。如果这是一个问题,我会把它放在答案中。但是,重点关注 OP 的核心问题,我选择不把它放在问题中。但是,是的,plt.tight_figure() 会做得很好。
    猜你喜欢
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多