Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

python - 更改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的间隔?)

  ask by Dax Feliz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...