Matplotlib:如何在柱子之间留空?

10 投票
1 回答
30846 浏览
提问于 2025-04-21 03:53

嗨,我开始使用matplotlib这个库,试着把网站上的示例代码改成我需要的样子。我有下面这段代码,基本上能实现我想要的效果,但每组的第三根柱子会和下一组的第一根柱子重叠。因为网络不好,无法上传图片,但如果能帮我解决这个问题就太好了。如果你能解释一下我哪里出错了,我会很感激。

谢谢,
汤姆

"""
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt


n_groups = 3

means_e1 = (20, 35, 30)
std_e1 = (2, 3, 4)

means_e2 = (25, 32, 34)
std_e2 = (3, 5, 2)

means_e3 = (5, 2, 4)
std_e3 = (0.3, 0.5, 0.2)

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.35

opacity = 0.4
error_config = {'ecolor': '0.3'}

rects1 = plt.bar(index , means_e1, bar_width,
                 alpha=opacity,
                 color='b',
                 yerr=std_e1,
                 error_kw=error_config,
                 label='Main')

rects2 = plt.bar(index + bar_width + 0.1, means_e2, bar_width,
                 alpha=opacity,
                 color='r',
                 yerr=std_e2,
                 error_kw=error_config,
                 label='e2')

rects3 = plt.bar(index + bar_width + bar_width + 0.2, means_e3, bar_width,
                 alpha=opacity,
                 color='g',
                 yerr=std_e3,
                 error_kw=error_config,
                 label='e3')

plt.xlabel('Dataset type used')
plt.ylabel('Percentage of reads joined after normalisation to 1 million reads')
plt.title('Application of Thimble on datasets, showing the ability of each stitcher option.')
plt.xticks(index + bar_width + bar_width, ('1', '2', '3'))
plt.legend()

plt.tight_layout()
plt.show()

1 个回答

12

这里的 bar_width + bar_width + 0.2 计算出来是 0.9。现在你又加了一根宽度为 bar_width(也就是 0.35)的柱子,所以总宽度变成了 1.25,这就超过了 1。因为 1 是每两个数据点之间的距离,所以就会出现重叠。

你可以选择增加数据点之间的距离(用 index = np.arange(0, n_groups * 2, 2) 来实现),或者把柱子的宽度减小,比如改成 0.2

撰写回答