gpt4 book ai didi

Python Plot 无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:45 24 4
gpt4 key购买 nike

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

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

最佳答案

条形图的位置有点偏离。您在 [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

关于Python Plot 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48128261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com