如何在不更改matplotlib中标签轴位置的情况下更改网格线的位置?

时间:2020-09-18 13:58:05

标签: python matplotlib

您好,有一种方法可以在不更改轴标签位置的情况下更改网格位置吗? 我想保留标签的正常显示位置,而无需指定,但将网格线置于特定位置。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# yvals = [floats]
# list_of_points = [[(x,y), (x,y), (x,y), ...], [...], ...]

ax.plot([i for i in range(len(y_vals))], y_vals, label=y_name)

for points, points_name in zip(list_of_points, list_of_points_names):
    xpoints = [v[0] for v in points]
    ypoints = [v[1] for v in points]
    ax.scatter(xpoints, ypoints, label=points_name)

points = []
for p in list_of_points:
    points += p

ax.set_xticks([p[0] for p in points])
ax.set_yticks([p[1] for p in points])
plt.grid()
ax.legend()
plt.show()

1 个答案:

答案 0 :(得分:1)

如果所需的所有网格线位置均与所需的所有刻度线位置不同,执​​行此操作的一种简单方法是对网格线使用次要刻度线(假设仅将主要刻度线显示为标记的刻度线,如下所示)在您的代码中。)

只需将代码中的plt.grid()替换为此:

ax.set_xticks(<list of vertical gridline positions>, minor=True)
ax.set_yticks(<list of horizontal gridline positions>, minor=True)
plt.grid(which='minor')