我对Python还不熟悉,我正试图在matplotlib的帮助下绘制一些数据。在
我试图对数据进行分组,但问题是组之间相互重叠。这是一张描述我的问题的图片:Problem
这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
n_groups = 3
credits = (market[0], market[1], market[2])
debits = (dmarket[0], dmarket[1], dmarket[2])
profits = (pmarket[0], pmarket[1], pmarket[2])
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.45
opacity = 0.4
error_config = {'ecolor': '0.3'}
rectsCredits = plt.bar(index, credits, bar_width,
alpha=opacity,
color='b',
error_kw=error_config,
label='Credit')
rectsDebits = plt.bar(index + bar_width, debits, bar_width,
alpha=opacity,
color='r',
error_kw=error_config,
label='Debit')
rectsProfits = plt.bar(index + 2*bar_width, profits, bar_width,
alpha=opacity,
color='g',
error_kw=error_config,
label='Profits')
plt.xticks(index + bar_width/2, ('Tariff Market', 'Wholesale Market', 'Balancing Market'))
plt.legend()
plt.tight_layout()
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2.,
1.01 * height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rectsCredits)
autolabel(rectsDebits)
autolabel(rectsProfits)
plt.show()
我不知道该怎么办。我想只有一个逻辑上的小问题我现在看不出来!在
横杆的位置有点偏了。在
[0, 1, 2]
(index
)插入第一个标签组,在[0.45, 1.45, 2.45]
(index + bar_width
)插入第二个标签组,在[0.9, 1.9, 2.9]
(index + 2*bar_width
)插入第三个标签组。每个条的宽度是0.45
,所以难怪这些重叠。在在下面的部分中,我只选择了一些用于可视化的数据,您必须插入或使用正确的值。在
如果将
bar_width
更改为1/3
,则组之间没有空白:如果您选择
^{pr2}$1/4
这样,每个组之间就有足够的空间容纳一个额外的条:但是标签还没有正确居中,但是可以通过在
plt.xticks
中使用新索引轻松修复:相关问题 更多 >
编程相关推荐