【问题标题】:Matplotlib - create a scatter plot with points that fill the available spaceMatplotlib - 使用填充可用空间的点创建散点图
【发布时间】:2020-05-02 00:56:01
【问题描述】:

我可以创建如下散点图:

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 接口。

【问题讨论】:

  • 一个混淆可能是点的大小用“显示坐标”表示,而点之间的间距用“数据坐标”表示。因此,每当 x 或 y 轴的限制发生变化(例如添加更多点)或绘图变大时,它们的关系就会发生变化。 This tutorial 给出了一些额外的解释。

标签: python matplotlib plot customization


【解决方案1】:
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()

【讨论】:

  • 谢谢 - 如何设置大小,使点足够大,因此它们之间没有空格,并且点之间没有重叠。
  • @baxx 查看更新的解决方案。根据您在原始问题中的要求,我尝试尽可能少地使用面向对象的接口。
  • 谢谢 - 但在我最初的问题中,它说我确实希望使用 OOP 界面,而不是我不使用。
  • 补丁解决方案看起来不错,但这似乎是最好的方法
猜你喜欢
  • 2020-05-31
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 2023-03-04
相关资源
最近更新 更多