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

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

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

那我就会这么做:

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

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

推荐答案

您可以使用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)功能将自动设置默认的xy限制.如果希望保持这些限制,只需更改记号的步长,那么可以使用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. 例如

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

Python相关问答推荐

使用SKLearn KMeans和外部生成的相关矩阵

如何随着收件箱的增加动态添加到HTML表的右下角?

修剪Python框架中的尾随NaN值

如何从不同长度的HTML表格中抓取准确的字段?

判断两极中N(N 2)列水平是否相等

Pandas使用过滤器映射多列

如何使用函数正确索引收件箱?

如何在telegram 机器人中发送音频?

Polars Select 多个元素产品

在Transformer中使用LabelEncoding的ML模型管道

仅对matplotlib的条标签中的一个条标签应用不同的格式

无法导入已安装的模块

如何在箱形图中添加绘制线的传奇?

从收件箱中的列中删除html格式

追溯(最近最后一次调用):文件C:\Users\Diplom/PycharmProject\Yolo01\Roboflow-4.py,第4行,在模块导入roboflow中

我如何根据前一个连续数字改变一串数字?

可以bcrypts AES—256 GCM加密损坏ZIP文件吗?

旋转多边形而不改变内部空间关系

在单次扫描中创建列表

numpy.unique如何消除重复列?