gpt4 book ai didi

python - 最初绘制正确设置所有轴的数据时执行的 matplotlib 函数的名称是什么?

转载 作者:行者123 更新时间:2023-12-01 07:45:33 25 4
gpt4 key购买 nike

当我在不设置任何参数的情况下使用 matplotlib 绘制一些数据时,数据会在 x 轴和 y 轴限制设置正确的情况下绘制,这意味着显示所有数据并且不会浪费空间(情况 1):

import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
x = range(10)

plt.plot(x,'-o',markersize='10')

plt.tight_layout()
plt.show()

结果:

case 1: initial plotting without any limits set

如果我为 e 设置一些限制。 G。 x 轴,即使使用 autoscale() 也不再自动缩放 y 轴(情况 2):

import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
x = range(10)

plt.plot(x,'-o',markersize='10')
plt.autoscale(enable=True,axis='y')
plt.xlim(7.5,11)
plt.tight_layout()
plt.show()

结果:

case 2: using x limits

问题:matplotlib 在内部使用哪个函数来确定两个轴的限制并更新情况 1 中的绘图?

背景:我想使用此函数作为为案例 2 重新实现/扩展此功能的基础。

最佳答案

@ImportanceOfBeingEarnest在下面的答案中指出,目前还没有这种自动化的方式。因此,如果您有兴趣了解如何重新缩放 y 轴,一种方法是重新计算相应的 y 值,然后使用 this 中指定的方法重新分配 y 限制。未接受的答案。我没有将其标记为重复,因为您的示例中存在某些不同的问题:

  • 首先(主要的),您仅绘制了 x 值。因此,要在另一个答案中应用该方法,我必须首先获取数组中的 y 值。这是使用 get_ydata()
  • 完成的
  • 其次,x 值从 range() 生成器更改为 NumPy 数组,因为前者不支持索引。
  • 第三,我必须使用变量来使 x 限制与函数保持一致。
<小时/>
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)

plt.plot(x,'-o',markersize='10')
x_lims = [7.5, 11]
plt.xlim(x_lims)

ax = plt.gca()
y = ax.lines[0].get_ydata()

def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx

y_low = y[find_nearest(x, x_lims[0])]
y_high = y[find_nearest(x, x_lims[1])]
ax.set_ylim(y_low, y_high)

plt.tight_layout()
plt.show()

enter image description here

关于python - 最初绘制正确设置所有轴的数据时执行的 matplotlib 函数的名称是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56478774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com