python - Matplotlib - 固定 x 轴刻度和自动缩放 y 轴

标签 python pandas matplotlib

我只想绘制数组的一部分,固定 x 部分,但让 y 部分自动缩放。我尝试如下所示,但它不起作用。

有什么建议吗?

import numpy as np
import matplotlib.pyplot as plt

data=[np.arange(0,101,1),300-0.1*np.arange(0,101,1)]

plt.figure()

plt.scatter(data[0], data[1])
plt.xlim([50,100])
plt.autoscale(enable=True, axis='y')

plt.show()

enter image description here

最佳答案

同时 Joe Kington当他建议只绘制必要的数据时,肯定会提出最明智的答案,在某些情况下,最好绘制所有数据并只缩放到某个部分。此外,最好有一个只需要轴对象的“autoscale_y”函数(即,与答案 here 不同,它需要直接使用数据。)

这是一个函数,它根据可见 x 区域中的数据重新缩放 y 轴:

def autoscale_y(ax,margin=0.1):
    """This function rescales the y-axis based on the data that is visible given the current xlim of the axis.
    ax -- a matplotlib axes object
    margin -- the fraction of the total height of the y-data to pad the upper and lower ylims"""

    import numpy as np

    def get_bottom_top(line):
        xd = line.get_xdata()
        yd = line.get_ydata()
        lo,hi = ax.get_xlim()
        y_displayed = yd[((xd>lo) & (xd<hi))]
        h = np.max(y_displayed) - np.min(y_displayed)
        bot = np.min(y_displayed)-margin*h
        top = np.max(y_displayed)+margin*h
        return bot,top

    lines = ax.get_lines()
    bot,top = np.inf, -np.inf

    for line in lines:
        new_bot, new_top = get_bottom_top(line)
        if new_bot < bot: bot = new_bot
        if new_top > top: top = new_top

    ax.set_ylim(bot,top)

这有点像 hack,在很多情况下可能行不通,但对于简单的情节来说,它很管用。

这是一个使用这个函数的简单例子:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-100,100,1000)
y = x**2 + np.cos(x)*100

fig,axs = plt.subplots(1,2,figsize=(8,5))

for ax in axs:
    ax.plot(x,y)
    ax.plot(x,y*2)
    ax.plot(x,y*10)
    ax.set_xlim(-10,10)

autoscale_y(axs[1])

axs[0].set_title('Rescaled x-axis')
axs[1].set_title('Rescaled x-axis\nand used "autoscale_y"')

plt.show()

enter image description here

关于python - Matplotlib - 固定 x 轴刻度和自动缩放 y 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461608/

相关文章:

python3将文件(从文件夹和子文件夹)转换为特定格式的json文件(项目包括文件夹名称和文件名)

python - 如何使 @decorator 和 @decorator(args) 共享相同的名称?

python - 如何在 pandas 数据框中引用以数字作为名称的列?

python - 如何只查看 pandas 数据框中的某些行?

python matplotlib blit 到图形的轴或侧面?

python - matplotlib中plt.plot()的第三个参数有什么作用?

python - watson-developer-cloud pip 模块抛出哪些异常

python - 将一列中的字典列表转换为同一数据框中的多列

python - Pandas 条形图呈灰色

python - 使用 pySerial 的 AT cmd 响应