gpt4 book ai didi

python - 跳过条形图中的零值——Matplotlib

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

我有一个绘制自定义条形图的代码:

def bar_chartQ2(sizes, colors, x_labels, c_labels, file_name):
y, x = sizes.shape
ind = np.arange(y)*8
width = 0.7

plt.figure()
for i in range(x):
plt.bar(ind + width*i, sizes[:, i], width, color=colors[i], label=c_labels[i])

c_labels = ['1', '2', '3', '4', '5', '6', '7', '8', 'Unknown']
x_labels = ['1)', '2)', '3)', '4)', '5)']
sizes = np.array([[2, 8, 2, 1, 0, 0, 0, 0, 1],
[2, 4, 6, 0, 0, 0, 1, 0, 1],
[2, 0, 0, 2, 5, 0, 0, 1, 3],
[1, 0, 0, 3, 2, 2, 4, 0, 2],
[1, 0, 1, 0, 1, 1, 4, 3, 2]])
colors = ['royalblue', 'red', 'orange', 'green', 'purple', 'deepskyblue', 'deeppink', 'limegreen', 'firebrick']

bar_chartQ2(sizes, colors, x_labels, c_labels, 'Q2')
plt.legend(loc=(1.2, 0.2), shadow=True)
plt.xticks(ind + x/2.0*width, x_labels)

plt.tight_layout()
plt.savefig(file_name+'.pdf', format='pdf', bbox_inches='tight')

到目前为止,结果如下:

enter image description here

我觉得这有点难以理解。

我想跳过大小 == 0 的条形,即防止同一项目的条形之间出现空白。

最佳答案

这是一个将所有数据绘制在单独轴上的解决方案:

import numpy 
from matplotlib import pyplot
import seaborn

c_labels = ['1', '2', '3', '4', '5', '6', '7', '8', 'Unknown']
colors = ['royalblue', 'red', 'orange', 'green', 'purple', 'deepskyblue', 'deeppink', 'limegreen', 'firebrick']
x_labels = ['1)', '2)', '3)', '4)', '5)']
sizes = numpy.array([
[2, 8, 2, 1, 0, 0, 0, 0, 1],
[2, 4, 6, 0, 0, 0, 1, 0, 1],
[2, 0, 0, 2, 5, 0, 0, 1, 3],
[1, 0, 0, 3, 2, 2, 4, 0, 2],
[1, 0, 1, 0, 1, 1, 4, 3, 2]
])

fig, axes = pyplot.subplots(ncols=sizes.shape[0], figsize=(10, 5), sharey=True)
for ax, height, title in zip(axes, sizes, x_labels):
ax.set_title(title)

left = numpy.arange(len(height)) + 1
ax.bar(left, height, color=colors)

ax.set_xticks(left)
ax.set_xticklabels(c_labels, rotation=45, rotation_mode='anchor', ha='right')

enter image description here

关于python - 跳过条形图中的零值——Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42725409/

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