Matplotlib 网格线
绘制添加网格线
应用 Pyplot 库, 您可以使用 grid() 函数在绘制时添加网格线。
实例
绘制时添加网格线:
import sysimport matplotlibmatplotlib.use('Agg')import numpy as npimport matplotlib.pyplot as pltx = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])plt.title("Sports Watch Data")plt.xlabel("Average Pulse")plt.ylabel("Calorie Burnage")plt.plot(x, y)plt.grid()plt.show()plt.savefig(sys.stdout.buffer)sys.stdout.flush()
结果:

指定要显示的网格线
您可以在grid() 函数使用 axis 参数来指定那一条网格线可以显示。
参数可设置的值有: ‘x’, ‘y’, 和 ‘both’. 默认值是 ‘both’.
实例
只显示 x 轴的网格线:
#Three lines to make our compiler able to draw:import sysimport matplotlibmatplotlib.use('Agg')import numpy as npimport matplotlib.pyplot as pltx = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])plt.title("Sports Watch Data")plt.xlabel("Average Pulse")plt.ylabel("Calorie Burnage")plt.plot(x, y)plt.grid(axis = 'x')plt.show()#Two lines to make our compiler able to draw:plt.savefig(sys.stdout.buffer)sys.stdout.flush()
结果:

实例
只显示 y 轴的网格线:
import sysimport matplotlibmatplotlib.use('Agg')import numpy as npimport matplotlib.pyplot as pltx = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])plt.title("Sports Watch Data")plt.xlabel("Average Pulse")plt.ylabel("Calorie Burnage")plt.plot(x, y)plt.grid(axis = 'y')plt.show()plt.savefig(sys.stdout.buffer)sys.stdout.flush()
结果:

为 Grid 设置线属性
您也可以设置网格的线的属性, 比如这样: grid(color = 'color', linestyle = 'linestyle', linewidth = number)。
实例
设置网格线的属性:
import sysimport matplotlibmatplotlib.use('Agg')import numpy as npimport matplotlib.pyplot as pltx = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])plt.title("Sports Watch Data")plt.xlabel("Average Pulse")plt.ylabel("Calorie Burnage")plt.plot(x, y)plt.grid(color = 'green', linestyle = '--', linewidth = 0.5)plt.show()#Two lines to make our compiler able to draw:plt.savefig(sys.stdout.buffer)sys.stdout.flush()
结果:
