Matplotlib:双轴图表没有按预期工作

时间:2018-06-06 14:44:43

标签: python matplotlib

您好,我的第一个matplotlib代码就在这里。

import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure() # Create matplotlib figure
ax = fig.add_subplot(111) # Create matplotlib axes

ind = np.arange(5)
avg_bar1 = (10,20,30,60,14)
avg_bar2 = (20,26,31,31,55)
avg_bar3 = (30,38,38,39,40)
avg_bar4 = (40,25,25,28,27)
avg = []
rects1 = plt.bar(ind, avg_bar1, 0.20, color='#68c7b7',label='bar1')
rects2 = plt.bar(ind + 0.20, avg_bar2, 0.20, color='#e19300', label='bar2')
rects3 = plt.bar(ind + 0.40, avg_bar3, 0.20, color='#969696', label='bar3')
rects4 = plt.bar(ind + 0.60, avg_bar4, 0.20, color='#17839a', label='bar4')

high_point_x = []
high_point_y = []


for i in range(0,5):
   single_bar_group={rects1[i].get_height():rects1[i].get_x() + rects1[i].get_wi                                                                 dth()/2.0,
                      rects2[i].get_height():rects2[i].get_x() + rects2[i].get_w                                                                 idth()/2.0,
                      rects3[i].get_height():rects3[i].get_x() + rects3[i].get_w                                                                 idth()/2.0,
                      rects4[i].get_height():rects4[i].get_x() +rects4[i].get_wi                                                                 dth()/2.0}

   height_list = list(single_bar_group.keys())
   height_list.sort(reverse=True)

   for single_height in height_list:
       high_point_y.append(single_height)
       high_point_x.append(single_bar_group[single_height])
       break

   ax.spines['right'].set_visible(False)
   ax.spines['left'].set_visible(False)
   ax.spines['top'].set_visible(False)
   ax.tick_params(
        axis = 'y',
        left = False,
        right = False

         )
ax2 = ax.twinx()
trend_line =ax2.plot(high_point_x,high_point_y,marker='o',color='#7cb85e',label=                                                                 'Trend Linei')
plt.xticks(ind+0.20, ('Q1 2017', 'Q2 2017', 'Q3 2017', 'Q4 2017', 'Q5 2017'))
ax2.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.tick_params(
        axis = 'y',
        left = False,
        right = False
        )

plt.savefig('foo.png', bbox_inches="tight", pad_inches=0)

我想构建组合图表(基本上是条形图组和条形图的平均值)。

但平均线看起来并不像预期,我相信y轴值也不合适。

任何人都可以帮忙解决为什么会出现这样的情况。

enter image description here

0 个答案:

没有答案