Pyplot - 正值和负值的条形图 [英] Pyplot - bar chart of positive and negative values

查看:149
本文介绍了Pyplot - 正值和负值的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望负向条向下,正向上,x轴(0行)在它们之间通过。我试过这个

  chart = fig.bar(x,negative_data,width = 35,color ='r')
ax2 = plt.gca()。twinx()
ax2.bar(x,positive_data,width = 35,color ='b')

但是相反,我会合并红色和白色条,两者都朝下。看来,数组negative_data / positive_data只指定了条的高度,但我如何指定方向?我需要一些东西来指定每个栏的顶部的坐标。

另外,如何使宽度合理,可能是动态的,因为图形是由用户调整大小的?

以下是宽度有问题的示例:

  x = [250,1500,2750,4250,6000,8500,13200] 
negative_data = [0,0,0,0,0,0,0]
positive_data = [3,0,0,0 ,1,0,0]

我怎样才能让这些看起来好看?

解决方案

您不需要添加双轴,您可以在同一轴上绘制两个条形图,如下所示:

  x =范围(7)
negative_data = [-1,-4,-3,-2,-6,-2 ,-8]
positive_data = [4,2,3,1,4,6,7,]

fig = plt.figure()
ax = plt.subplot (111)
ax.bar(x,negative_data,width = 1,color ='r')
ax.bar(x,positive_data,width = 1,color ='b')



宽度为1的条形图将填充轴并按照原样放大调整大小。

I want the negative bars to be facing downwards, and the positive upwards, with the x-axis(0-line) passing right between them. I tried this

chart = fig.bar(x, negative_data, width=35, color='r')
ax2 = plt.gca().twinx()
ax2.bar(x, positive_data, width=35, color='b')

But instead, I get merged red and white bars, both facing downwards. It seems that the arrays negative_data/positive_data only specify the height of the bar, but how do I specify the orientation? I need something to specify the coordinates of the tops of each bar.

Also, how do I make the widths be something reasonable, possibly dynamic as the graph is resized by user?

Here is an example of problematic widths:

x = [250, 1500, 2750, 4250, 6000, 8500, 13200]
negative_data = [0, 0, 0, 0, 0, 0, 0]
positive_data = [3, 0, 0, 0, 1, 0, 0]

How can I make the plot of those look nice?

解决方案

You don't need to add a twin axis, you can plot both bar charts on the same axis like this:

x = range(7)
negative_data = [-1,-4,-3,-2,-6,-2,-8]
positive_data = [4,2,3,1,4,6,7,]

fig = plt.figure()
ax = plt.subplot(111)
ax.bar(x, negative_data, width=1, color='r')
ax.bar(x, positive_data, width=1, color='b')

Bars with a width of one will fill the axes and will scale with the figure as it is resized.

这篇关于Pyplot - 正值和负值的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆