改变“滴答频率".在matplotlib的x或y轴上? [英] Changing the "tick frequency" on x or y axis in matplotlib?

查看:105
本文介绍了改变“滴答频率".在matplotlib的x或y轴上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修复python如何绘制数据.

I am trying to fix how python plots my data.

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

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

然后我会做:

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

,x轴的刻度线间隔为5.是否有办法使间隔的间隔为1?

and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?

推荐答案

您可以使用plt.xticks明确设置要在标记上打勾的位置:

You could explicitly set where you want to tick marks with 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()


(为了防止min(x)max(x)是浮点数而不是整数,使用了np.arange而不是Python的range函数.)


(np.arange was used rather than Python's range function just in case min(x) and max(x) are floats instead of ints.)

plt.plot(或ax.plot)功能将自动设置默认的xy限制.如果您希望保留这些限制,而只是更改刻度线的步长,则可以使用ax.get_xlim()来发现Matplotlib已设置的限制.

The plt.plot (or ax.plot) function will automatically set default x and y limits. 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.

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

这篇关于改变“滴答频率".在matplotlib的x或y轴上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆