【问题标题】:How to plot grouped bars如何绘制分组条形图
【发布时间】:2021-11-25 05:55:30
【问题描述】:

我想在我的图表中制作多个条形图,每个条形图的颜色应该不同。我已经写好了代码:

 barWidth = 0.125

ET1 = [24,78,90]
ET2 = [45,73,52]
ET3 = [18,38,29]
ET4 = [25,18,13]
ET5 = [45,72,41]

br1 = np.arange(len(ET1))
br2 = [x + barWidth for x in br1]
br3 = [x + barWidth for x in br2]
br4 = [x + barWidth for x in br3]
br5 = [x + barWidth for x in br4]

plt.bar(br1, ET1, color= 'r', width = barWidth,
        edgecolor ='grey', label ='e+1')
plt.bar(br2, ET2, color= 'b',width = barWidth,
        edgecolor ='grey', label ='2e+1')
plt.bar(br3, ET3, color= 'y',width = barWidth,
        edgecolor ='grey', label ='3e+1')
plt.bar(br4, ET4, color= 'g',width = barWidth,
        edgecolor ='grey', label ='5e+1')
plt.bar(br3, ET5, color= 'pink',width = barWidth,
        edgecolor ='grey', label ='7e+1')

plt.xlabel('SIZE', fontweight ='bold', fontsize = 15)
plt.ylabel('TIME', fontweight ='bold', fontsize = 15)
plt.xticks([r + barWidth for r in range(len(ET1))],[11,18,44])

plt.legend()
plt.savefig('Comp1.png')
plt.show()

所有条形的代码运行良好,但问题是我没有得到第三个数据input(ET3(3e+1)) 的条形,它应该是黄色的,但我没有在我的图表中得到它。

【问题讨论】:

  • 好吧,你写 ed5ecolor 用 5 替换 g ....。您还需要一个较小的条宽来容纳 5 个条。 (也许barWidth=0.18?)
  • @JohanC 谢谢我已经编辑了问题请看。
  • 在您写 br3 时,您需要plt.bar(br5, ET5, ... 最后一个酒吧。
  • @JohanC 非常感谢先生。

标签: python matplotlib bar-chart


【解决方案1】:
  • 现有代码的问题已通过注释解决,并且是由拼写错误plt.bar(br3, ET5,... 造成的,其中br3 应为br5,正如@JohanC 所指出的那样
  • 通过将数据加载到 pandas 并使用pandas.DataFrame.plot(使用matplotlib 作为默认后端)进行绘图,可以更轻松地创建分组条形图。
    • 这将代码从 22 行减少到 11 行(不包括注释代码,因为这是可选的)。
import pandas as pd

# create the dataframe from the existing data
df = pd.DataFrame({'e+1': ET1, '2e+1': ET2, '3e+1': ET3, '5e+1': ET4, '7e+1': ET5}, index=[11, 18, 44])

# display(df)
    e+1  2e+1  3e+1  5e+1  7e+1
11   24    45    18    25    45
18   78    73    38    18    72
44   90    52    29    13    41

# plot the dataframe and format it
ax = df.plot(kind='bar', width=.75, rot=0, color=['r', 'b', 'y', 'g', 'pink'], ec='gray')
ax.legend(loc=2)
ax.set_xlabel('SIZE', fontweight ='bold', fontsize = 15)
ax.set_ylabel('TIME', fontweight ='bold', fontsize = 15)

# add annotations if desired
for c in ax.containers:
    # set the bar label
    ax.bar_label(c, padding=3, rotation=0)
    
# pad the spacing between the number and the edge of the figure
ax.margins(y=0.1)

# extract the figue object and save
ax.get_figure().savefig('Comp1.png')

【讨论】:

    猜你喜欢
    • 2018-01-06
    • 1970-01-01
    • 2020-12-09
    • 2021-01-12
    • 1970-01-01
    • 2012-10-23
    • 2020-03-22
    • 2019-08-16
    相关资源
    最近更新 更多