gpt4 book ai didi

python - 在 matplotlib 的单个直方图中添加水平线

转载 作者:行者123 更新时间:2023-12-01 08:15:41 25 4
gpt4 key购买 nike

我想在一组条形图中的每个条形旁边绘制中值位置及其值。

鉴于 matplotlib example

import numpy as np
import matplotlib.pyplot as plt


data = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[139361, 331509, 343164, 781380, 52269]]

columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]

values = np.arange(0, 2500, 500)
value_increment = 1000

# Get some pastel shades for the colors
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
n_rows = len(data)

index = np.arange(len(columns)) + 0.3
bar_width = 0.4

# Initialize the vertical-offset for the stacked bar chart.
y_offset = np.zeros(len(columns))

# Plot bars and create text labels for the table
cell_text = []
for row in range(n_rows):
plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
y_offset = y_offset + data[row]
cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])
# Reverse colors and text labels to display the last value at the top.
colors = colors[::-1]
cell_text.reverse()

# Add a table at the bottom of the axes
the_table = plt.table(cellText=cell_text,
rowLabels=rows,
rowColours=colors,
colLabels=columns,
loc='bottom')

# Adjust layout to make room for the table:
plt.subplots_adjust(left=0.2, bottom=0.2)

plt.ylabel("Loss in ${0}'s".format(value_increment))
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Loss by Disaster')

plt.show()

我尝试将其插入到创建条形的 for 循环中

for row in range(n_rows):
plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
med = np.median(data[row])
xmin = row
xmax= (row + 1)
label = str(med) + "%"
plt.hlines(med, xmin, xmax, label=label, linestyle="dashed")
y_offset = y_offset + data[row]
cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])

但是线条太长:如何获取条形宽度? 加号标签不显示并且条形图远离单元格中心......!

barplot

最佳答案

定位:

我稍微修改了你的代码。重点是 bar 默认情况下会以居中的方式绘制条形(请参阅始终有帮助的 docs),因此您需要将 hlines 设置为从中心 - 0.5 条形宽度到中心+ 0.5 条宽度:

# Plot bars and create text labels for the table
cell_text = []
medians = []
for row in range(n_rows):
plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
y_offset = y_offset + data[row]
cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])
medians.append(np.median(data[row]))
# Reverse colors and text labels to display the last value at the top.
colors = colors[::-1]
cell_text.reverse()
# Draw the medians
h_width = 0.5 * bar_width
plt.hlines(medians, xmin=index-0.5*bar_width, xmax=index+0.5*bar_width, color="k", linestyle="dashed", linewidth=1)

这就是你得到的:

enter image description here

现在是标签:

如果您将 hlineslabel=label 一起使用,您仍然需要使用 plt.legend() 绘制图例。

然而,问题是所有值都将出现在图例中,并且很难(如果不是不可能)将每个值与相应的行关联起来,特别是如果它们都具有相同的颜色。更好的解决方案可能是将值放在每条虚线旁边。要实现此目的,您可以使用 annotations :

# add the annotations (just after the part from above)
for i, med in enumerate(medians):
plt.annotate(str(med) + "%", xy=(index[i], med),
ha='center', va='bottom'
)

所以你最终会得到:

enter image description here





希望对您有所帮助,祝您编码愉快!


关于python - 在 matplotlib 的单个直方图中添加水平线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54991834/

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