假设我有一个Pandas Dataframe ,有几千行长,我想用Matplotlib来绘制它们。
temps = df['temperature']plt.plot(temps)
temps = df['temperature']
plt.plot(temps)
我希望x轴沿着的值从0开始,以25结束。如下所示:
|||||||________________________0 5 10 15 20 25
|
|________________________
0 5 10 15 20 25
我该怎么做才不会影响我的计划?
xienkqul1#
您可以使用plt.xlim函数。
plt.xlim
temps = df['temperature']plt.plot(temps)plt.xlim(0, 25)
plt.xlim(0, 25)
但是matplotlib文档要求每个人都使用面向对象的API,并且远离高级的plt绘图函数。
matplotlib
plt
temps = df['temperature']fig, ax = plt.subplots()ax.plot(temps)ax.set_xlim(0, 25)
fig, ax = plt.subplots()
ax.plot(temps)
ax.set_xlim(0, 25)
现在,如果您想要控制沿着x轴的刻度数,您可以手动设置它们,如下所示:
fig, ax = plt.subplots()ax.plot(temps)ax.set_xlim(0, 25)ax.set_xticks([0, 5, 10, 15, 20, 25])
ax.set_xticks([0, 5, 10, 15, 20, 25])
也可以使用.ticker API如下所示:
.ticker
import matplotlib.pyplot as pltfrom matplotlib.ticker import MultipleLocatortemps = [i ** 2 for i in range(25)]fig, ax = plt.subplots()ax.plot(temps)ax.set_xlim(0, 25)# from the lower x-limit to the upper x-limit# place a tick every multiple of 5ax.xaxis.set_major_locator(MultipleLocator(5))
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
temps = [i ** 2 for i in range(25)]
# from the lower x-limit to the upper x-limit
# place a tick every multiple of 5
ax.xaxis.set_major_locator(MultipleLocator(5))
如果您有超过25个值,并希望将它们放置在0-25的任意范围内,则可以使用刻度定位器和刻度格式化器,如下所示:
import matplotlib.pyplot as pltfrom matplotlib.ticker import LinearLocatortemps = [i ** 2 for i in range(1_000)]fig, ax = plt.subplots()ax.plot(temps)ax.margins(x=0)n = 6 # ticks including: 0, 5, 10, 15, 20, 25ax.xaxis.set_major_locator(LinearLocator(n))ax.xaxis.set_major_formatter(lambda val, pos: pos * (n - 1))
from matplotlib.ticker import LinearLocator
temps = [i ** 2 for i in range(1_000)]
ax.margins(x=0)
n = 6 # ticks including: 0, 5, 10, 15, 20, 25
ax.xaxis.set_major_locator(LinearLocator(n))
ax.xaxis.set_major_formatter(lambda val, pos: pos * (n - 1))
1条答案
按热度按时间xienkqul1#
设置xlim
您可以使用
plt.xlim
函数。但是
matplotlib
文档要求每个人都使用面向对象的API,并且远离高级的plt
绘图函数。设置xticks
现在,如果您想要控制沿着x轴的刻度数,您可以手动设置它们,如下所示:
也可以使用
.ticker
API如下所示:使用多个值
如果您有超过25个值,并希望将它们放置在0-25的任意范围内,则可以使用刻度定位器和刻度格式化器,如下所示: