Matplot lib:条形图未正确分组

时间:2018-06-21 12:07:30

标签: python matplotlib

enter image description here我下面的代码无法正确地将我的matplot库图分组。

  fig = plt.figure() # Create matplotlib figure
  ax = fig.add_subplot(111) # Create matplotlib axes
  ind = np.arange(5)
  width = 0.20
  avg_bar1 = (10,20,30,60,14)
  avg_bar2 = (10,50,30,60,35)
  avg_bar3 = (10,90,30,60,12)
  avg_bar4 = (10,70,30,60,23)
  avg_bar5 = (10,50,30,40,80)


  rects1 = plt.bar(ind, avg_bar1, label='bar1')
  rects2 = plt.bar(ind+width, avg_bar2, label='bar2')
  rects3 = plt.bar(ind+width, avg_bar3, label='bar3')
  rects4 = plt.bar(ind+width, avg_bar4, label='bar4')
  rects5 = plt.bar(ind+width, avg_bar5, label='bar5')


  plt.xticks(ind+0.20, ('Q1 2017', 'Q2 2017', 'Q3 2017', 'Q4 2017', 'Q5 2017'))
  img_path = str(str(user)+str(req_id)+str(slide_id)+'.png')
  plt.savefig(img_path, bbox_inches="tight", pad_inches=0)

  return img_path

我不知道为什么此条形图按xticks中的四分之一进行分组。

1 个答案:

答案 0 :(得分:1)

我只能在这里猜测,但是我想您想将每个小节偏移不同的数量。最好将这种偏移量选择为关于某些整数位置对称。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure() # Create matplotlib figure
ax = fig.add_subplot(111) # Create matplotlib axes
ind = np.arange(5)
width = 0.15
avg_bar1 = (10,20,30,60,14)
avg_bar2 = (10,50,30,60,35)
avg_bar3 = (10,90,30,60,12)
avg_bar4 = (10,70,30,60,23)
avg_bar5 = (10,50,30,40,80)


rects1 = plt.bar(ind-2*width, avg_bar1, width=width, label='bar1')
rects2 = plt.bar(ind-1*width, avg_bar2, width=width, label='bar2')
rects3 = plt.bar(ind+0*width, avg_bar3, width=width, label='bar3')
rects4 = plt.bar(ind+1*width, avg_bar4, width=width, label='bar4')
rects5 = plt.bar(ind+2*width, avg_bar5, width=width, label='bar5')


plt.xticks(ind, ('Q1 2017', 'Q2 2017', 'Q3 2017', 'Q4 2017', 'Q5 2017'))

plt.show()

enter image description here