Python 在网格和x27的交点处绘制标记;小蜱
我希望生成一个带有网格的绘图,以便在主刻度处绘制一条完整的线,并用正方形(或任何可自定义标记)标记次要刻度的交点 以下是我试图实现的一个示例: 我使用Python 在网格和x27的交点处绘制标记;小蜱,python,python-3.x,matplotlib,Python,Python 3.x,Matplotlib,我希望生成一个带有网格的绘图,以便在主刻度处绘制一条完整的线,并用正方形(或任何可自定义标记)标记次要刻度的交点 以下是我试图实现的一个示例: 我使用RegularPolyCollection,用以下代码生成了这个图: import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import RegularPolyCollection # Define dimensions and create
RegularPolyCollection
,用以下代码生成了这个图:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import RegularPolyCollection
# Define dimensions and create plotting objects
width_squares = 6
height_squares = 6
figure = plt.figure()
ax = figure.add_subplot(111)
# Define ticks
x_minors = np.linspace(0, width_squares, 5 * width_squares + 1)
x_majors = np.linspace(0, width_squares, width_squares + 1)
y_minors = np.linspace(0, height_squares, 5 * height_squares + 1)
y_majors = np.linspace(0, height_squares, height_squares + 1)
# Set ticks
ax.set_xticks(x_majors)
ax.set_xticks(x_minors, minor=True)
ax.set_yticks(y_majors)
ax.set_yticks(y_minors, minor=True)
# Define window
ax.set_xlim((0, 6))
ax.set_ylim((0, 6))
# Draw the point collection: squares rotated by 45°
offsets = [(x, y) for x in x_minors for y in y_minors]
points = RegularPolyCollection(
4,
sizes=(1,),
offsets=offsets,
color=('lightgray',),
transOffset=ax.transData,
rotation=0.7857
)
ax.add_collection(points)
# Draw the grid at major ticks
ax.grid(True, which='major', axis='both', color='lightgray')
plt.show()
然而,我实际上试图制作的情节要大得多,而且性能也岌岌可危。
不幸的是,绘制大量点集合非常耗时
我还根据进行了调查,并通过将linestyle
设置为“None”
绘制垂直线得出了类似的结果,以便只标记交叉点,但时间消耗与采集方法类似
我怀疑plt.grid
函数应该有一组参数来产生我想要的结果,但我无法理解markevery
和其他关键字参数的效果(虽然我确实理解它们与Line2D
对象一起使用时的含义)
有没有标准的方法来制作这样的网格?如果是这样的话,有没有可能使它不那么耗时?我不确定您是否尝试了共享链接中提供的答案之一的版本。我必须做的主要修改是在获取x-tick和y-tick数据时打开小刻度。您是否有比较此方法和Line2D的时间复杂度的数字
# Draw the grid at major ticks
ax.grid(True, which='major', axis='both')
ax.set_aspect('equal')
def set_grid_cross(ax):
xticks = ax.get_xticks(minor=True)
yticks = ax.get_yticks(minor=True)
xgrid, ygrid = np.meshgrid(xticks, yticks)
kywds = dict()
grid_lines = ax.plot(xgrid, ygrid, 'o', ms=2, color='lightgray', alpha=0.5)
set_grid_cross(ax)
看起来不错,但在我的例子中(6个大刻度高,48个宽,1个大刻度5个小刻度),它需要500到1000毫秒,而采集和测线方法都需要100到300毫秒。我想问题在于绘图操作:因为网格实际上很轻,所以我假设Matplotlib可以更智能地绘制网格。。。无论如何,感谢您对
np.meshgrid
的深入了解,它看起来确实不错。@右腿您的意思是绘制线条集合比调用grid
更快?@ImportanceOfBeingErnest:可能是因为对于这个小数据集,线条绘制和线条集合的性能优于数据集,但随着数据集的增长,网格交叉并获胜。右腿仍然需要确认这一点