Skip to main content
 首页 » 编程设计

python之在网格的小刻度的交叉点绘制标记

2024年12月31日8me-sa

我想生成一个带有网格的图,以便在主要刻度处绘制一条完整的线,并且次刻度的交叉点用正方形(或任何可自定义的标记)标记。

这是我正在尝试实现的示例:

我使用 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() 

但是,我实际尝试制作的情节要大得多,并且性能受到威胁。 不幸的是,绘制大量的点非常耗时。

我还调查了基于this question , 我通过将 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)