PyPlot-设置p的网格线间距

2024-04-29 10:21:54 发布

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

我有一个由Networkx创建的无向图,我正在使用pyplot显示它,我希望允许用户指定网格线之间的间距。我不想手动输入勾号,因为这需要知道绘图的最终大小(如果有方法,我想知道),这可能会根据显示的图形而有所不同。

是否有任何方法允许您设置间距量?我找了一会儿,什么也找不到,谢谢。

下面的代码与创建绘图而不是图形有关。

#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")

我需要找到一种让网格具有由用户定义的间距间隔的方法。我已经找到了方法,但是它也依赖于你想要多少网格线,这会导致这些线在图上的间隔不均匀


Tags: 方法代码用户networkx图形绘图间隔on
3条回答

不确定这是否违背了您不手动播放节拍的愿望,但您可以使用matplotlib.ticker将节拍设置为给定的间隔:

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='-')

可以使用ticker设置网格的tick locations。用户可以指定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一起使用,您可以使用上面的子块(或其他函数)创建轴,并像这样将该轴传递给draw

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自己绘制网格,如本例中的https://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()

相关问题 更多 >