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

时间:2018-12-13 16:40:49

标签: python-3.x matplotlib scatter-plot

我有这个散点图:

enter image description here

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

enter image description here

用于复制情节的代码:

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()

1 个答案:

答案 0 :(得分:1)

也许以下内容符合要求。您可以将次要刻度用于网格,将主要刻度用于标签。

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()

enter image description here