简体   繁体   English

使用matplotlib自动设置条形图的y轴限制

[英]Automatically setting y-axis limits for bar graph using matplotlib

Here's an example of graphing large values. 这是绘制大值的示例。

import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [1000, 1002, 1001, 1003, 1005]
plt.bar(x,y) 
plt.show()

The y-axis starts at 0, so the bars all look equal. y轴从0开始,因此条都看起来相等。 I know you can use plt.ylim to manually set the limits, but is there a way for matplotlib to automatically (and smartly) set the limits to reasonable values (like 998-1008), and also perhaps show an axis break? 我知道你可以使用plt.ylim手动设置限制,但matplotlib是否有办法自动(并巧妙地)将限制设置为合理的值(如998-1008),也可能显示轴断点?

A little bit of simple algebra will help fix the limits: 一点点简单的代数将有助于修复限制:

import matplotlib.pyplot as plt
import math
x = [1,2,3,4,5]
y = [1000, 1002, 1001, 1003, 1005]
low = min(y)
high = max(y)
plt.ylim([math.ceil(low-0.5*(high-low)), math.ceil(high+0.5*(high-low))])
plt.bar(x,y) 
plt.show()

In this way, you are able to find the difference between your y-values and use them to set the scale along the y-axis. 通过这种方式,您可以找到y值之间的差异,并使用它们来设置沿y轴的比例。 I used math.ceil (as opposed to math.floor) in order to obtain the values you specified and ensure integers. 我使用math.ceil(而不是math.floor)来获取您指定的值并确保整数。

As far as an axis break goes, I'd suggest looking at this example . 就轴断裂而言,我建议看一下这个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM