【问题标题】:Python Pandas Plotting Two BARH side by sidePython Pandas 并排绘制两个 BARH
【发布时间】:2017-10-18 08:23:01
【问题描述】:

我正在尝试制作一个类似这样的情节,

左侧图表(带有图例的图)源自df_2,右侧图表源自df_1

但是,我不能让两个图并排共享 y 轴。

这是我目前的绘图方式:

df_1[target_cols].plot(kind='barh', x='LABEL', stacked=True, legend=False)
df_2[target_cols].plot(kind='barh', x='LABEL', stacked=True).invert_xaxis()
plt.show()

代码将在两个不同的“画布”中生成两个图。

  1. 如何让它们并排共享 y 轴?
  2. 如何删除左侧图表(源自df_2 的图表)y 轴上的标签?

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:

    您可以使用plt.subplots(sharey=True) 创建共享子图。然后将数据框绘制到两个子图。

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    a = np.random.randint(5,15, size=10)
    b = np.random.randint(5,15, size=10)
    
    df = pd.DataFrame({"a":a})
    df2 = pd.DataFrame({"b":b})
    
    fig, (ax, ax2) = plt.subplots(ncols=2, sharey=True)
    
    ax.invert_xaxis()
    ax.yaxis.tick_right()
    
    df["a"].plot(kind='barh', x='LABEL',  legend=False, ax=ax)
    df2["b"].plot(kind='barh', x='LABEL',ax=ax2)
    plt.show()
    

    【讨论】:

      【解决方案2】:

      一开始是用

      fig, axes = plt.subplots(ncols=2, sharey=True)
      axes[0], axes[1]
      

      但由于某些原因无法将 y 刻度放在右侧(因此它们看起来居中)。现在使用 'ax' 和 'ax2' 和 ax.yaxis.tick_right() 有效!

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2016-08-01
      • 2019-10-31
      • 2020-05-30
      • 2023-01-03
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多