使用Matplotlib导入的Python中具有2个比例(y轴)的条形图

时间:2018-12-11 00:40:51

标签: python matplotlib graph

因此,我正在编写一个条形图,该条形图具有相同程序中其他地方的预测总利润,实际总利润和错误百分比计算。使用此图,我试图制作第二个y轴,以使左侧上限为50000,右侧上限为100:这分别是利润和百分比误差。我相信我已经完成了大部分工作,但事实是,条形图仅响应其中一个刻度,但不会两者都响应。如何获得3个与正确比例相关的条形图(左手2个,右手1个)?另外,请忽略图像中的代码与我发布的图像不同的事实,以及第二个轴不正确的事实。我用发布的代码修复了该问题,我只需要我所要求的。代码和输出:

    # Create a bar graph
objects = ('Pre_Total_Profit', 'Act_Total_Profit', 'Percent_Error')
y_pos = np.arange(len(objects))
performance = [tpp, tp, pe]
fig, ax1 = plt.subplots()                                 # Apply subplots to x-axis (for 2 y axis)
ax2 = ax1.twinx()                                       # Create second y-axis
ax1.set_ylabel('Dollars', color='g')        # Label y-axis in green
ax2.set_ylabel('Percent', color='m')           # Label second y-axis in magenta
ax1.set_ylim([0, 50000])
ax2.set_ylim([0, 100])

plt.bar(y_pos, performance, align='center', alpha=0.5, color='g')
plt.xticks(y_pos, objects)
plt.title('Total Profits and Percent Error')

plt.show()

要澄清一下:左边的2个图形(“ Pre_Total_Profit”和“ Act_Total_Profit”)应填充到我绘制的红色,但不要多,因为它仅指的是左手轴(“ Dollars ”)。右图(“ Percent_Error”)应为84,仅指右轴。该信息是在程序的较早版本中获取的,并放置在文本表中,我已将其链接到我感兴趣的3个值的一部分。如果有什么办法可以使自己更加清楚,请告诉我。 Current Graph

Desired Graph

Reference Table

1 个答案:

答案 0 :(得分:1)

所以我发现了我的问题,这很简单。我仍在学习,所以我没有意识到性能是针对图形上条形的,除非我仍然对此表示错误。无论哪种方式,修复程序都是添加第二个性能变量(performance2)并用尺寸填充它,以便它只会创建最右边的小节(误差百分比)。如果有人对此感兴趣,或者有人需要它,这就是代码和输出。

  # Create a bar graph
objects = ('Pre_Total_Profit', 'Act_Total_Profit', 'Percent_Error')
y_pos = np.arange(len(objects))
performance = [tpp, tp, pe]
performance2 = [0, 0, pe]
fig, ax1 = plt.subplots()                                 # Apply subplots to x-axis (for 2 y axis)
ax2 = ax1.twinx()                                       # Create second y-axis
ax1.set_ylabel('Dollars', color='g')        # Label y-axis in green
ax2.set_ylabel('Percent', color='m')           # Label second y-axis in magenta
ax1.set_ylim([0, (tpp+tp)])
ax2.set_ylim([0, 100])
# When graph shows, ignore the excess cyan on the left 2 bars.
ax1.bar(y_pos, performance, align='center', color='g')  # Left 2 bars (Pre/Act Profits) will show in green/centered
ax2.bar(y_pos, performance2, align='center', alpha=0.5, color='c')  # Right bar (%error) will show in cyan/centered
plt.xticks(y_pos, objects)
plt.title('Total Profits and Percent Error')

plt.show()

如果有人对完整代码感兴趣,请询问。那是比这部分大得多的程序,但这是我遇到的问题。感谢那些发表评论并给我一个主意的人。

Graph