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

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

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

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


当前回答

你可以循环标签,并显示或隐藏你想要的:

   for i, label in enumerate(ax.get_xticklabels()):
        if i % interval != 0:
            label.set_visible(False)

其他回答

我喜欢这个解决方案(来自Matplotlib绘图Cookbook):

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

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

tick_spacing = 1

fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.show()

这个解决方案让你通过给ticker.MultipleLocater()的数字显式控制刻度间距,允许自动确定限制,并且便于以后读取。

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

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

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函数。

纯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的默认行为,因为没有指定刻度)。

xmarks=[i for i in range(1,length+1,1)]

plt.xticks(xmarks)

这对我很有效

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

length = 5