如何将散点图的网格居中?

How to center the grid of a plot on scatter points?

我有这个散点图:

我想移动网格,使每个点(绿色方块)都被网格的单元包围。例如:

重现剧情的代码:

import matplotlib.pyplot as plt

data = [24, 24, 24, 16, 16, 2, 2, 2]
x = list(range(0, len(data)))
y = list(range(0, 25))

plt.scatter(x, data, marker='s', c='g', s=100)
plt.yticks(y)
plt.xticks(x)

plt.grid(True)
plt.show()

也许像下面这样的东西符合要求。您可以对网格使用次要刻度,对标签使用主要刻度。

import numpy as np
import matplotlib.pyplot as plt

data = [24, 24, 24, 16, 16, 2, 2, 2]
x = list(range(0, len(data)))

fig, ax = plt.subplots()
ax.scatter(x, data, marker='s', c='g', s=49)

ax.set_yticks(np.arange(25))
ax.set_yticks(np.arange(25+1)-0.5, minor=True)

ax.set_xticks(np.arange(len(data)))
ax.set_xticks(np.arange(len(data)+1)-0.5, minor=True)

ax.grid(True, which="minor")
ax.set_aspect("equal")
plt.show()