简体   繁体   English

matplotlib.pyplot - 仅修复一个轴限制,将另一个设置为auto

[英]matplotlib.pyplot - fix only one axis limit, set other to auto

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.] . 在此图中,x轴限制设置为[0., 1.] I need to set the upper y axis limit to 1. leaving the lower limit to whatever the min value in m2 is (ie: let python decide the lower limit). 我需要 Y轴限值设置为1离开下限到任何在最小值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. 在这里建议如何设置'auto'作为上限,但使用matplotlib.pyplot保持固定的下限 ,但两个命令似乎都不起作用。 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. 它们都正确地将y轴的上限设置为1.但它们也强制下限为0.这是我不想要的。

I'm using Python 2.7.3 and Matplotlib 1.2.1 . 我正在使用Python 2.7.3Matplotlib 1.2.1

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 autoscaling if needed 或者,如果需要,您可以重新启用自动缩放

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

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