Pyplot 打印分组条形图中第一个位置重叠的所有条形

问题描述 投票:0回答:1

我正在生成一个分组条形图,显示哪些订单将在一周中的哪一天到达。 我的代码如下:

plt.figure(1)
x = np.arange(7)
width = .1
for j in range(9):
    print(pdChart[j])
    plt.bar((j-4)/10, pdChart[j], width, label=list(flavors.keys())[j])

plt.xticks(x,daysOWeek) 
plt.ylabel("Orders")
plt.legend()
plt.title("Preferred Delivery Days")
plt.show()

但是,它会在星期一位置打印所有内容。 因此,输出仅是“星期一”数据,最高日的总数显示为每种口味的条形高度。 各个条形图都正确对齐等等。 但周二、周三等没有任何事情

[420 352 425 391 423 388 387]
[0 0 0 0 0 0 0]
[857 840 881 900 852 851 874]
[248 234 246 239 242 223 249]
[235 243 227 249 270 251 249]
[1670 1822 1835 1818 1796 1804 1764]
[427 461 430 490 428 435 444]
[102 101  94  86 102 110 107]
[718 743 718 705 741 781 716]

所以数据是正确的。 但我得到的不是每行 7 个条,而是 425、0、900、249 等,仅显示本周最高的一天总数,这就是为什么我认为它是重叠的。

python matplotlib
1个回答
0
投票

bar chart

您使用标量值来定位风味/蔬菜的所有条形 - 请改用值数组

import matplotlib.pyplot as plt
import numpy as np

vegetables = '''\
Bell Peppers
Broccoli
Carrots
Cucumbers
Lettuce
Onions
Potatoes
Spinach
Tomatoes
'''.splitlines()

pdChart = [
 [ 420,  352,  425,  391,  423,  388,  387],
 [ 0.1,    0,    0,    0,    0,    0,    0],
 [ 857,  840,  881,  900,  852,  851,  874],
 [ 248,  234,  246,  239,  242,  223,  249],
 [ 235,  243,  227,  249,  270,  251,  249],
 [1670, 1822, 1835, 1818, 1796, 1804, 1764],
 [ 427,  461,  430,  490,  428,  435,  444],
 [ 102,  101,   94,   86,  102,  110,  107],
 [ 718,  743,  718,  705,  741,  781,  716]]

# I prefer to fill legend rows first https://stackoverflow.com/a/66783666/2749397
reorder=lambda hl,nc:(sum((lis[i::nc]for i in range(nc)),[])for lis in hl)
for i, (label, orders) in enumerate(zip(vegetables, pdChart)):
    plt.bar(np.arange(7)+(i-4)/12, orders, label=label, width=1/14)
plt.legend(*reorder(plt.gca().get_legend_handles_labels(),5), ncol=5,
  loc=(0, 1.04), borderaxespad=0, fontsize='small')
plt.xticks(range(7), 'Mon Tue Wed Thu Fri Sat Sun'.split());
plt.gcf().set_layout_engine('constrained')
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.