14

The following MWE produces a simple scatter plot:

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 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).

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.

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.

I'm using Python 2.7.3 and Matplotlib 1.2.1.

4

1 回答 1

23

如果只是担心正在绘制大量数据,为什么不检索绘图的 y 下限并在设置限制时使用它呢?

plt.ylim(plt.ylim()[0], 1.0)

或类似地用于特定轴。有点难看,但我看不出它为什么不起作用。


问题实际上在于,在绘图之前设置限制会禁用自动缩放。默认情况下,x 轴和 y 轴的限制都是(0.0, 1.0),这就是 y 下限保持为 0 的原因。

解决方案只是在调用所有绘图命令后设置绘图限制。或者,如果需要,您可以重新启用自动缩放

于 2013-09-07T19:11:13.687 回答