首页 > 解决方案 > Matplotlib - 使用填充可用空间的点创建散点图

问题描述

我可以创建一个散点图,如下所示:

fig, ax = plt.subplots()
x1 = [1, 1, 2]
y1 = [1, 2, 1]
x2 = [2]
y2 = [2]
ax.scatter(x1, y1, color="red", s=500)
ax.scatter(x2, y2, color="blue", s=500)

这使

在此处输入图像描述

我想要的是以下内容(为糟糕的油漆工作道歉):

在此处输入图像描述

我正在绘制所有整数值的数据,所以它们都在网格上。我希望能够控制分散标记的大小,以便我可以在点周围有空白,或者我可以使点足够大,这样它们周围就没有空白(就像我在上面的油漆图像)。

注意 - 理想情况下,解决方案将在纯 matplotlib 中,使用他们在文档中建议的 OOP 接口。

标签: pythonmatplotlibplotcustomization

解决方案


import matplotlib.pyplot as plt
import matplotlib as mpl

# X and Y coordinates for red circles
red_xs = [1,2,3,4,1,2,3,4,1,2,1,2]
red_ys = [1,1,1,1,2,2,2,2,3,3,4,4]

# X and Y coordinates for blue circles
blu_xs = [3,4,3,4]
blu_ys = [3,3,4,4]

# Plot with a small markersize
markersize = 5
fig, ax = plt.subplots(figsize=(3,3))
ax.plot(red_xs, red_ys, marker="o", color="r", linestyle="", markersize=markersize)
ax.plot(blu_xs, blu_ys, marker="o", color="b", linestyle="", markersize=markersize)
plt.show()

小标记

# Plot with a large markersize
markersize = 50
fig, ax = plt.subplots(figsize=(3,3))
ax.plot(red_xs, red_ys, marker="o", color="r", linestyle="", markersize=markersize)
ax.plot(blu_xs, blu_ys, marker="o", color="b", linestyle="", markersize=markersize)
plt.show()

在此处输入图像描述

# Plot with using patches and radius
r = 0.5
fig, ax = plt.subplots(figsize=(3,3))
for x, y in zip(red_xs, red_ys):
    ax.add_patch(mpl.patches.Circle((x,y), radius=r, color="r"))
for x, y in zip(blu_xs, blu_ys):
    ax.add_patch(mpl.patches.Circle((x,y), radius=r, color="b"))
ax.autoscale()
plt.show()

在此处输入图像描述


推荐阅读