matplotlib - PyPlot设置 plot的网格线间距

用Networkx创建无向图,正在使用pyplot显示该图,我想允许用户指定网格线之间的间距,

有没有允许设置间距量的方法?

下面的代码与plot的创建有关。


#Spacing between each line
intervals = float(sys.argv[1])

nx.draw(displayGraph, pos, node_size = 10)
plt.axis('on')
plt.grid('on')
plt.savefig("test1.png")

时间:


import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

fig,ax=plt.subplots()

#Spacing between each line
intervals = float(sys.argv[1])

loc = plticker.MultipleLocator(base=intervals)
ax.xaxis.set_major_locator(loc)
ax.yaxis.set_major_locator(loc)

# Add the grid
ax.grid(which='major', axis='both', linestyle='-')

用户可以指定MultipleLocator的输入,该输入将在视图间隔上设置一个间距”,这是一个例子:


from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np

# Two example plots
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)

spacing = 0.5 # This can be your user specified spacing. 
minorLocator = MultipleLocator(spacing)
ax1.plot(9 * np.random.rand(10))
# Set minor tick locations.
ax1.yaxis.set_minor_locator(minorLocator)
ax1.xaxis.set_minor_locator(minorLocator)
# Set grid to use minor tick locations. 
ax1.grid(which = 'minor')

spacing = 1
minorLocator = MultipleLocator(spacing)
ax2.plot(9 * np.random.rand(10))
# Set minor tick locations.
ax2.yaxis.set_minor_locator(minorLocator)
ax2.xaxis.set_minor_locator(minorLocator)
# Set grid to use minor tick locations. 
ax2.grid(which = 'minor')

plt.show()

Two subplots with different grids.

要与Networkx一起使用,可以使用subplot (或其他函数)创建轴,并将轴传递给如下所示的绘图


nx.draw(displayGraph, pos, ax=ax1, node_size = 10)

或者可以像在问题中那样调用nx.draw,然后使用gca获取当前坐标轴:


nx.draw(displayGraph, pos, node_size = 10)
ax1 = plt.gca()

例如,你可以使用xlim获取x轴的范围和用户指定的间隔,你应该可以使用ax.axvline绘制网格,http://stackoverflow.com/a/9128244/566035

希望此帮助。

这是个例子。


from pylab import *

fig = figure()
ax = fig.add_subplot(111)

ax.plot([1,2,3, 15],[2,3,4, 25],'ro')
xmin,xmax = xlim()
user_interval = 1.5
for _x in np.arange(xmin, xmax, user_interval):
 ax.axvline(x=_x, ls='-')
draw()

...