Python matplotlib.pyplot - 仅修复一个轴限制,将其他设置为自动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18676022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
matplotlib.pyplot - fix only one axis limit, set other to auto
提问by Gabriel
The following MWE
produces a simple scatter plot:
下面MWE
生成一个简单的散点图:
import numpy as np
import matplotlib.pyplot as plt
# Generate some random two-dimensional data:
m1 = np.random.normal(size=100)
m2 = np.random.normal(scale=0.5, size=100)
# Plot data with 1.0 max limit in y.
plt.figure()
# Set x axis limit.
plt.xlim(0., 1.0)
# Plot points.
plt.scatter(m1, m2)
# Show.
plt.show()
In this plot the x axis limits are set to [0., 1.]
. I need to set the uppery axis limit to 1. leaving the lower limit to whatever the min value in m2
is (ie: let python
decide the lower limit).
在此图中,x 轴限制设置为[0., 1.]
。我需要设定上y轴的极限为1离开下限到任何min值在m2
是(即:让python
决定的下限值)。
In this particular case I could just use plt.ylim(min(m2), 1.0)
but my actual code is far more complicated with lots of things being plotted so doing this is not really an option.
在这种特殊情况下,我可以只使用,plt.ylim(min(m2), 1.0)
但我的实际代码要复杂得多,要绘制很多东西,所以这样做并不是一个真正的选择。
I've tried setting:
我试过设置:
plt.ylim(top=1.)
and also:
并且:
plt.gca().set_ylim(top=1.)
as advised here How to set 'auto' for upper limit, but keep a fixed lower limit with matplotlib.pyplot, but neither command seems to work. They both correctly set the upper limit in the y axis to 1. but they also force a lower limit of 0. which I don't want.
如此处所建议的如何为上限设置“自动”,但使用 matplotlib.pyplot 保持固定的下限,但两个命令似乎都不起作用。他们都正确地将 y 轴的上限设置为 1。但他们也强制下限为 0。这是我不想要的。
I'm using Python 2.7.3
and Matplotlib 1.2.1
.
我正在使用Python 2.7.3
和Matplotlib 1.2.1
。
采纳答案by Sajjan Singh
If the concern is simply that a lot of data is being plotted, why not retrieve the plot's lower y-limit and use that when setting the limits?
如果担心只是绘制了大量数据,为什么不检索绘图的下限 y 并在设置限制时使用它?
plt.ylim(plt.ylim()[0], 1.0)
Or analogously for a particular axis. A bit ugly, but I see no reason why it shouldn't work.
或者对于特定的轴类似。有点难看,但我看不出它不应该工作的理由。
The issue actually resides in the fact that setting the limits before plotting disables autoscaling. The limits for both the x and y axes are, by default, (0.0, 1.0)
, which is why the lower y limit remains at 0.
问题实际上在于在绘图之前设置限制会禁用自动缩放。默认情况下,x 轴和 y 轴的限制均为(0.0, 1.0)
,这就是 y 下限保持为 0 的原因。
The solution is simply to set the plot limits after calling all plot commands. Or you can re-enable autoscalingif needed
解决方案只是在调用所有绘图命令后设置绘图限制。或者您可以根据需要重新启用自动缩放