Python Matplotlib-更改自动轴范围
我对数据使用自动轴范围 例如,当我使用-29和+31之间的x数据时Python Matplotlib-更改自动轴范围,python,matplotlib,Python,Matplotlib,我对数据使用自动轴范围 例如,当我使用-29和+31之间的x数据时 ax = plt.gca() xsta, xend = ax.get_xlim() 我得到-30和40,这不适合描述数据范围。我希望看到轴范围四舍五入到5,即限制为-30和35 有可能吗?或者,是否可以获得x轴数据的精确范围(-29,31),然后编写算法手动更改该范围(使用set_xlim) 感谢帮助。要将轴xlim设置为数据的精确范围,请将ax.xlim()方法与内置的min()和max()功能结合使用: #x could
ax = plt.gca()
xsta, xend = ax.get_xlim()
我得到-30和40,这不适合描述数据范围。我希望看到轴范围四舍五入到5,即限制为-30和35
有可能吗?或者,是否可以获得x轴数据的精确范围(-29,31),然后编写算法手动更改该范围(使用set_xlim
)
感谢帮助。要将轴xlim设置为数据的精确范围,请将
ax.xlim()
方法与内置的min()
和max()
功能结合使用:
#x could be a list like [0,3,5,6,15]
ax = plt.gca()
ax.xlim([min(x), max(x)]) # evaluates to ax.xlim([0, 15]) with example data above
当您知道需要5的倍数时,请根据数据的x范围修改限制:
import math
import matplotlib.pyplot as pet
#your plotting here
xmin = min( <data_x> )
xmax = max( <data_x> )
ax = plt.gca()
ax.set_xlim( [5*math.floor(xmin/5.0), 5*math.ceil(xmax/5.0)] )
导入数学
将matplotlib.pyplot作为pet导入
#你在这里策划的
xmin=min()
xmax=最大值()
ax=plt.gca()
ax.set_xlim([5*math.floor(xmin/5.0),5*math.ceil(xmax/5.0)])
请注意,由于
int/int
忽略了小数部分,因此必须按浮点5.0
进行除法。例如5*math.ceil(6/5)
中的xmax=6
将返回5
,这将切断您的数据,而5*math.ceil(6/5.0)
给出所需的5*math.ceil(1.2)=5*2=10
,首先,让我们建立一个简单的示例:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
plt.show()
如果您想知道手动指定所述内容的数据范围,可以使用:
ax.xaxis.get_data_interval()
ax.yaxis.get_data_interval()
然而,想要改变数据限制的简单填充是很常见的。在这种情况下,请使用ax.margins(某些百分比)
。例如,这将用数据范围的5%填充限制:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
ax.margins(0.05)
plt.show()
要返回到原始场景,可以手动使轴限制仅使用5的倍数(但不更改刻度等):
我们还可以通过对每个轴的定位器进行子类化来完成相同的任务:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoLocator
class MyLocator(AutoLocator):
def view_limits(self, vmin, vmax):
multiplier = 5.0
vmin = multiplier * np.floor(vmin / multiplier)
vmax = multiplier * np.ceil(vmax / multiplier)
return vmin, vmax
fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
ax.xaxis.set_major_locator(MyLocator())
ax.yaxis.set_major_locator(MyLocator())
ax.autoscale()
plt.show()
使用
axis
函数。是的,我也有这个想法,但如果图形上有许多绘图,则意味着必须分别检查每个绘图。我在找get_data_interval函数。是的,get_data_interval
就是我要找的。谢谢
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoLocator
class MyLocator(AutoLocator):
def view_limits(self, vmin, vmax):
multiplier = 5.0
vmin = multiplier * np.floor(vmin / multiplier)
vmax = multiplier * np.ceil(vmax / multiplier)
return vmin, vmax
fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
ax.xaxis.set_major_locator(MyLocator())
ax.yaxis.set_major_locator(MyLocator())
ax.autoscale()
plt.show()