【问题标题】:How to add a forth bar on a group barchart using matplotlib and seaborn in Python?如何在 Python 中使用 matplotlib 和 seaborn 在组条形图上添加第四条?
【发布时间】:2019-11-06 00:03:53
【问题描述】:

我正在尝试创建一个组条形图来显示不同机器学习分类器实现的准确度、精度、召回率和 f1 分数。当我为每个分类器使用三个条时,组条形图可以正常工作,但当我添加第四个时,它看起来很奇怪。具体来说,条之间的间隙消失,第四条与其他条重叠。这是我使用三个条时的样子:

这就是我尝试添加第四个时的样子:

N = 9
ind = np.arange(N)  # location of groups
width = 0.27       # width of bars

fig = plt.figure()
ax = fig.add_subplot(111)

rects1 = ax.bar(ind, Precision, width, color='r')

rects2 = ax.bar(ind+width, Recall, width, color='g')

rects3 = ax.bar(ind+width*2, F1, width, color='b')

rects4 =  ax.bar(ind+width*3, Accuracy, width, color='y')

ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels(Model,rotation=90)
ax.legend( (rects1[0], rects2[0], rects3[0]), ('Precision', 'Recall','F1 Score') )

def autolabel(rects):
    for rect in rects:
        h = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h*100),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
autolabel(rects4)

fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 20
fig_size[1] = 15
plt.rcParams["figure.figsize"] = fig_size

plt.show()

我是 Python 新手,因此我们将不胜感激。

【问题讨论】:

  • @Sheldore 谢谢,这解决了我的问题。如果您将其添加为正常回复,很高兴为您竖起大拇指并接受此答案。

标签: python-3.x matplotlib bar-chart data-visualization seaborn


【解决方案1】:

问题是您当前的间距是 0.27。当您有 4 个条时,这将导致 0.27*4 = 1.08 间距,而相应的条的间距为 1。因此,您的条开始重叠。

一种硬编码的解决方案是将 0.27 替换为更小的值,例如 0.2。这将在相邻条之间留下 1-0.2*4 = 0.2 的间距。

其他明智的解决方案是使用 spacing = 1/(nbars+1) 之类的方法根据条数计算间距,其中 +1 是添加额外空间

P.S:@Leporello 指出的 Python 2 用户

使用spacing = 1.0/(nbars+1)

【讨论】:

  • Python 2 用户注意:请改用spacing = 1.0/(nbars+1)。 (见stackoverflow.com/questions/21316968/…
  • @Leporello :哈哈,谢谢你的提示。我会用你的名字把它添加到答案中
猜你喜欢
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2018-12-17
相关资源
最近更新 更多