更改matplotlib中x或y轴上的“刻度频率”?

本文翻译自:Changing the “tick frequency” on x or y axis in matplotlib?

I am trying to fix how python plots my data. 我正在尝试修复python如何绘制我的数据。

Say

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

and

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

Then I would do: 然后我会做:

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

and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1? 并且x轴的刻度线以5的间隔绘制。是否有办法使其显示1的间隔?


#1楼

参考:https://stackoom.com/question/qu7Y/更改matplotlib中x或y轴上的-刻度频率


#2楼

You could explicitly set where you want to tick marks with plt.xticks : 您可以使用plt.xticks显式设置要在标记上plt.xticks

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

For example, 例如,

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 was used rather than Python's range function just in case min(x) and max(x) are floats instead of ints.) (以防min(x)max(x)是浮点数而不是整数的情况,使用了np.arange而不是Python的range函数。)


The plt.plot (or ax.plot ) function will automatically set default x and y limits. plt.plot (或ax.plot )函数将自动设置默认的xy限制。 If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set. 如果您希望保留这些限制,而只是更改刻度线的步长,则可以使用ax.get_xlim()来发现Matplotlib已设置的限制。

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

The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. 默认的刻度格式设置器应将刻度值四舍五入为有意义的有效数字位数。 However, if you wish to have more control over the format, you can define your own formatter. 但是,如果希望对格式有更多控制,则可以定义自己的格式器。 For example, 例如,

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

Here's a runnable example: 这是一个可运行的示例:

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

#3楼

Another approach is to set the axis locator: 另一种方法是设置轴定位器:

import matplotlib.ticker as plticker

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

There are several different types of locator depending upon your needs. 根据您的需要,有几种不同类型的定位器。

Here is a full example: 这是一个完整的示例:

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

#4楼

This is an old topic, but I stumble over this every now and then and made this function. 这是一个古老的话题,但是我时不时地碰到这个问题,并做了这个功能。 It's very convenient: 这很方便:

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)

One caveat of controlling the ticks like this is that one does no longer enjoy the interactive automagic updating of max scale after an added line. 像这样控制刻度线的一个警告是,添加行之后,不再享受最大比例的交互式自动魔术更新。 Then do 然后做

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

and run the resadjust function again. 并再次运行resadjust函数。


#5楼

I developed an inelegant solution. 我开发了一个优雅的解决方案。 Consider that we have the X axis and also a list of labels for each point in X. 考虑我们有X轴,还有X中每个点的标签列表。

Example: 例:
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabels,rotation=45)
plt.show()
Let's say that I want to show ticks labels only for 'feb' and 'jun' 假设我只想显示“ feb”和“ 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() 

#6楼

This is a bit hacky, but by far the cleanest/easiest to understand example that I've found to do this. 这有点棘手,但到目前为止,我发现这样做最干净/最容易理解的示例。 It's from an answer on SO here: 这是从SO的答案中获得的:

Cleanest way to hide every nth tick label in matplotlib colorbar? 隐藏matplotlib颜色栏中的每个第n个刻度标签的最干净方法?

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

Then you can loop over the labels setting them to visible or not depending on the density you want. 然后,您可以遍历标签,根据所需的密度将其设置为可见或不可见。

edit: note that sometimes matplotlib sets labels == '' , so it might look like a label is not present, when in fact it is and just isn't displaying anything. 编辑:请注意,有时matplotlib会设置标签== '' ,因此它看起来好像不存在标签,而实际上它却只是不显示任何内容。 To make sure you're looping through actual visible labels, you could try: 为确保您遍历实际可见标签,可以尝试:

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)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值