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

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

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

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


当前回答

如果有人对一般的一行程序感兴趣,只需获取当前的刻度,并通过对每个其他刻度进行采样来使用它来设置新的刻度。

ax.set_xticks(ax.get_xticks()[::2])

其他回答

我想出了一个不优雅的解决方案。假设我们有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()

纯Python实现

下面是所需功能的纯python实现,它可以处理任何具有正、负或混合值的数值序列(int或float),并允许用户指定所需的步长:

import math

def computeTicks (x, step = 5):
    """
    Computes domain with given step encompassing series x
    @ params
    x    - Required - A list-like object of integers or floats
    step - Optional - Tick frequency
    """
    xMax, xMin = math.ceil(max(x)), math.floor(min(x))
    dMax, dMin = xMax + abs((xMax % step) - step) + (step if (xMax % step != 0) else 0), xMin - abs((xMin % step))
    return range(dMin, dMax, step)

样例输出

# Negative to Positive
series = [-2, 18, 24, 29, 43]
print(list(computeTicks(series)))

[-5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]

# Negative to 0
series = [-30, -14, -10, -9, -3, 0]
print(list(computeTicks(series)))

[-30, -25, -20, -15, -10, -5, 0]

# 0 to Positive
series = [19, 23, 24, 27]
print(list(computeTicks(series)))

[15, 20, 25, 30]

# Floats
series = [1.8, 12.0, 21.2]
print(list(computeTicks(series)))

[0, 5, 10, 15, 20, 25]

# Step – 100
series = [118.3, 293.2, 768.1]
print(list(computeTicks(series, step = 100)))

[100, 200, 300, 400, 500, 600, 700, 800]

示例使用

import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(computeTicks(x))
plt.show()

注意,x轴的整数值之间均匀间隔为5,而y轴的间隔不同(matplotlib的默认行为,因为没有指定刻度)。

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

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()

这有点俗气,但到目前为止,这是我找到的最干净/最容易理解的例子。这句话来自这里SO的回答:

最干净的方法隐藏每n勾标签在matplotlib色条?

for label in ax.get_xticklabels()[::2]:
    label.set_visible(False)

然后你可以循环标签,根据你想要的密度将它们设置为可见或不可见。

编辑:注意,有时matplotlib设置标签== ",所以它可能看起来像一个标签不存在,而实际上它是,只是没有显示任何东西。为了确保你在循环实际可见的标签,你可以尝试:

visible_labels = [lab for lab in ax.get_xticklabels() if lab.get_visible() is True and lab.get_text() != '']
plt.setp(visible_labels[::2], visible=False)

如果你只是想把间距设置为一个简单的一行和最小的样板:

plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1))

对小蜱虫也很有效:

plt.gca().xaxis.set_minor_locator(plt.MultipleLocator(1))

有点满口,但很紧凑