Py学习  »  Python

Python帮助-设置x限制的间隔[duplicate]

Claire Harris • 4 年前 • 980 次点击  

x = [0,5,9,10,15]

y = [0,1,2,3,4]

然后我会:

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53031
 
980 次点击  
文章 [ 10 ]  |  最新文章 4 年前
Greenstick
Reply   •   1 楼
Greenstick    6 年前

下面是所需功能的纯python实现,它处理任何带有正值、负值或混合值的数字序列(int或float):

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
    """
    import math as Math
    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()
Gary Steele
Reply   •   2 楼
Gary Steele    4 年前

如果您只想设置一个简单的一行与最小样板的间距:

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

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

有点饱,但很紧凑

BartoszKP Piyush Gupta
Reply   •   3 楼
BartoszKP Piyush Gupta    6 年前
xmarks=[i for i in range(1,length+1,1)]

plt.xticks(xmarks)

如果希望在[1,5]之间(包括1和5)打勾,则替换

length = 5
Deninhos
Reply   •   4 楼
Deninhos    8 年前

我想出了一个不雅的解决办法。考虑到我们有X轴和X.中每个点的标签列表。

例子:
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']
假设我只想给'feb'和'jun'显示ticks标签
xlabelsnew = []
for i in xlabels:
    if i not in ['feb','jun']:
        i = ' '
        xlabelsnew.append(i)
    else:
        xlabelsnew.append(i)
很好,现在我们有一份假标签清单。首先,我们绘制了原始版本。
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabels,rotation=45)
plt.show()
现在,修改版。
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabelsnew,rotation=45)
plt.show()
Tompa
Reply   •   5 楼
Tompa    8 年前

这是一个老话题,但我时不时地会遇到这个问题,并制作了这个函数。非常方便:

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)

像这样控制勾号的一个注意事项是,在添加一行之后,用户不再享受max scale的交互式自动图像更新。那就去吧

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

并再次运行resadjust函数。

Community Jon McAuliffe
Reply   •   6 楼
Community Jon McAuliffe    6 年前

Cleanest way to hide every nth tick label in matplotlib colorbar?

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)
glopes
Reply   •   7 楼
glopes    7 年前

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

ax.set_xticks(ax.get_xticks()[::2])
jthomas
Reply   •   8 楼
jthomas    8 年前

我喜欢这个解决方案 Matplotlib Plotting 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() ,允许自动确定限值,并且便于以后阅读。

robochat
Reply   •   9 楼
robochat    4 年前

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

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()
unutbu
Reply   •   10 楼
unutbu    10 年前

您可以显式地设置要在其中打勾的标记 plt.xticks :

plt.xticks(np.arange(min(x), max(x)+1, 1.0))

例如,

import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()

np.arange 使用的而不是Python的 range 以防万一 min(x) max(x) 是浮点数而不是整数。)


plt.plot (或 ax.plot x y ax.get_xlim() 以发现Matplotlib已经设置了哪些限制。

start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))

ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))

下面是一个可运行的示例:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()