【问题标题】:Plotting multiple barplots on the same ax在同一轴上绘制多个条形图
【发布时间】:2019-07-15 14:44:24
【问题描述】:

我想使用相同的斧头在一行上绘制多个条形图,但似乎 pandas 绘图函数每次都会删除我之前的绘图。

例如:

import pandas as pd
import pylab as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'lab':['D', 'E', 'F'], 'val':[10, 30, 20]})
df.plot.bar(x='lab', y='val', rot=0, ax=ax)
df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
df.plot.bar(x='lab', y='val', rot=0, ax=ax)
ax.set_xlim(-.5, 6)
plt.show()

给我

我尝试使用 pandas 函数的xticks 参数,但没有成功。

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

您需要设置条在 X 轴上的位置

https://matplotlib.org/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py

men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)

ind = np.arange(len(men_means))  # the x locations for the groups
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std,
                color='SkyBlue', label='Men')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std,
                color='IndianRed', label='Women')

请注意“ind”部分 - 用于确定条形的位置。另请注意,条形图的颜色已拼出。

【讨论】:

    【解决方案2】:

    好的,看来我每次都必须提供所有刻度

    fig, ax = plt.subplots()
    
    df = pd.DataFrame({'lab':['A', 'B', 'C', 'D', 'E', 'F'], 'val':[10, 30, 20, 0, 0, 0]})
    df.plot.bar(x='lab', y='val', rot=0, ax=ax)
    df = pd.DataFrame({'lab':['A', 'B', 'C', 'D', 'E', 'F'], 'val':[0, 0, 0, 10, 30, 20]})
    df.plot.bar(x='lab', y='val', rot=0, ax=ax)
    
    plt.show()
    

    【讨论】:

      【解决方案3】:

      您可能希望在绘图之前合并两个数据框。

      import pandas as pd
      import matplotlib.pyplot as plt
      
      fig, ax = plt.subplots()
      df1 = pd.DataFrame({'lab':['D', 'E', 'F'], 'val':[10, 30, 20]})
      df2 = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
      
      df1.append(df2).plot.bar(x='lab', y='val', rot=0, ax=ax)
      
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-01
        • 2016-10-09
        • 1970-01-01
        • 2022-08-21
        • 2020-05-06
        • 2016-08-25
        • 1970-01-01
        • 2018-02-08
        相关资源
        最近更新 更多