【问题标题】:matplotlib uneven group size bar charts side-by-sidematplotlib 不均匀组大小条形图并排
【发布时间】:2017-01-27 02:20:07
【问题描述】:

我正在尝试绘制具有不同条形大小并且可能具有不同组大小的数据组。如何将属于同一组的条(显示为相同颜色)分组,以便它们并排? (类似于this,除了相同的颜色要并排)

width = 0.50      
groupgap=2
y1=[20,80]
y2=[60,30,10]
x1 = np.arange(len(y1))
x2 = np.arange(len(y2))+groupgap
ind = np.concatenate((x1,x2))
fig, ax = plt.subplots()
rects1 = ax.bar(x1, y1, width, color='r',  ecolor= "black",label="Gender")
rects2 = ax.bar(x2, y2, width, color='b',  ecolor= "black",label="Type")
ax.set_ylabel('Population',fontsize=14)
ax.set_xticks(ind)
ax.set_xticklabels(('Male', 'Female','Student', 'Faculty','Others'),fontsize=14)
ax.legend()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    使用类别之间的差距 (groupgap) 的想法确实是一种方法。您只需要添加第一组的长度即可:

    x2 = np.arange(len(y2))+groupgap+len(y1)
    

    这是我使用groupgap=1的完整示例:

    import matplotlib.pyplot as plt
    import numpy as np
    
    width = 1      
    groupgap=1
    y1=[20,80]
    y2=[60,30,10]
    x1 = np.arange(len(y1))
    x2 = np.arange(len(y2))+groupgap+len(y1)
    ind = np.concatenate((x1,x2))
    fig, ax = plt.subplots()
    rects1 = ax.bar(x1, y1, width, color='r',  edgecolor= "black",label="Gender")
    rects2 = ax.bar(x2, y2, width, color='b',  edgecolor= "black",label="Type")
    ax.set_ylabel('Population',fontsize=14)
    ax.set_xticks(ind)
    ax.set_xticklabels(('Male', 'Female','Student', 'Faculty','Others'),fontsize=14)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多