我试图修复python如何绘制我的数据。 说:

x = [0,5,9,10,15]
y = [0,1,2,3,4]

matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()

x轴的刻度以5为间隔绘制。有没有办法让它显示1的间隔?


当前回答

另一种方法是设置轴定位器:

import matplotlib.ticker as plticker

loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)

根据您的需要,有几种不同类型的定位器。

下面是一个完整的例子:

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.show()

其他回答

一般化的一行程序,只导入Numpy:

ax.set_xticks(np.arange(min(x),max(x),1))

在问题的背景下设置:

import numpy as np
import matplotlib.pyplot as plt 
fig, ax = plt.subplots()
x = [0,5,9,10,15]
y = [0,1,2,3,4]
ax.plot(x,y)
ax.set_xticks(np.arange(min(x),max(x),1))
plt.show()

工作原理:

图中,ax = plt.subplots()给出了包含坐标轴的ax对象。 np.arange(min(x),max(x),1)给出了一个区间为1的数组,从x的最小值到x的最大值。这是我们想要的新x刻度。 ax.set_xticks()改变ax对象上的刻度。

另一种方法是设置轴定位器:

import matplotlib.ticker as plticker

loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)

根据您的需要,有几种不同类型的定位器。

下面是一个完整的例子:

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.show()
xmarks=[i for i in range(1,length+1,1)]

plt.xticks(xmarks)

这对我很有效

如果你想要[1,5](1到5包括在内)之间的刻度,那么替换

length = 5

这是一个老话题了,但我偶尔会遇到这个问题,然后做了这个功能。非常方便:

import matplotlib.pyplot as pp
import numpy as np

def resadjust(ax, xres=None, yres=None):
    """
    Send in an axis and I fix the resolution as desired.
    """

    if xres:
        start, stop = ax.get_xlim()
        ticks = np.arange(start, stop + xres, xres)
        ax.set_xticks(ticks)
    if yres:
        start, stop = ax.get_ylim()
        ticks = np.arange(start, stop + yres, yres)
        ax.set_yticks(ticks)

像这样控制刻度的一个警告是,一个人不再享受在添加一行后最大刻度的交互式自动更新。然后做

gca().set_ylim(top=new_top) # for example

并再次运行resadjust函数。

我想出了一个不优雅的解决方案。假设我们有X轴和X中每个点的标签列表。

Example:
import matplotlib.pyplot as plt

x = [0,1,2,3,4,5]
y = [10,20,15,18,7,19]
xlabels = ['jan','feb','mar','apr','may','jun']
Let's say that I want to show ticks labels only for 'feb' and 'jun'
xlabelsnew = []
for i in xlabels:
    if i not in ['feb','jun']:
        i = ' '
        xlabelsnew.append(i)
    else:
        xlabelsnew.append(i)
Good, now we have a fake list of labels. First, we plotted the original version.
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabels,rotation=45)
plt.show()
Now, the modified version.
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabelsnew,rotation=45)
plt.show()