如何在Python中绘制网格到绘图上?

2024-04-26 08:38:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚用Python中的pylab完成了绘制一个图的代码,现在我想在散点图上叠加一个10x10的网格。我该怎么做?

我当前的代码如下:

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.show()

其输出为:

Without grid

我想要的是以下输出:

With grid

编辑:根据Andrey Sobolev的回答添加了一个示例


Tags: 代码numpy网格fig绘制pltaxfigure
3条回答

要使用pyplot.grid

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.grid()
plt.show()

ax.xaxis.gridax.yaxis.grid可以控制网格线属性。

Enter image description here

要在每个刻度上显示网格线,请添加

plt.grid(True)

例如:

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.scatter(x, y)
plt.grid(True)

plt.show()

enter image description here


此外,您可能需要自定义样式(例如实线而不是虚线),添加:

plt.rc('grid', linestyle="-", color='black')

例如:

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.rc('grid', linestyle="-", color='black')
plt.scatter(x, y)
plt.grid(True)

plt.show()

enter image description here

相关问题 更多 >