Python Plot无法正常工作

时间:2018-01-06 14:18:41

标签: python matplotlib

我是Python的新手,我试图在matplotlib的帮助下绘制一些数据。

我正在尝试对数据进行分组,但问题是这些组相互重叠。这是描述我的问题的图片:Problem

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()

我不知道该怎么办。我认为现在只有一点我没看到的逻辑问题!

1 个答案:

答案 0 :(得分:3)

酒吧的位置有点偏。您在[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,则各组之间不会有空格:

bar_width = 1 / 3

enter image description here

如果您选择1/4之类的内容,那么它将在每个组之间有一个额外的空格:

bar_width = 1 / 4

enter image description here

但标签尚未正确居中,但可以通过在plt.xticks中使用新索引轻松修复:

bar_width = 1 / 4
plt.xticks(index + bar_width, ('Tariff Market', 'Wholesale Market', 'Balancing Market'))

enter image description here

相关问题