python - 根据函数绘制 PatchCollection

标签 python matplotlib plot

对于该站点是全新的,对于 Python 也是相当新的,因此感谢您的帮助和提示。

我有一些 (x,y) 的数据,它们围绕一个中心形成几条近乎圆形的曲线。但为了示例,我只是创建了一些 (x,y) 形成的圆圈。

现在,我想绘制这些并用颜色填充这些多边形之间的空间,比方说通过函数获得的一些 (z) 值,以便每个“环”都有自己的阴影。

这是我现在想通的。

import matplotlib.pyplot as plt
import numpy as np
from math import sin, cos
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection

r = np.array([0.1, 0.2, 0.3, 0.4, 0.5 ,0.6, 0.7, 0.8, 0.9, 1.0])

fig, ax = plt.subplots(1)
ax.set_xlim([-1.1, 1.1])
ax.set_ylim([-1.1, 1.1])

x=[]
y=[]
patches = []
colors=np.array([0.9,0.8, 0.1, 0.1, 0.1, 0.4, 0.2,0.8,0.1, 0.9])




for radius in r:
    for phi in np.linspace(0, 360, 200, endpoint=True):
        x.append(radius*cos(np.deg2rad(phi)))
        y.append(radius*sin(np.deg2rad(phi)))
    points = np.vstack([x,y]).T
    polygon = Polygon(points,False)
    patches.append(polygon)

p = PatchCollection(patches, cmap="Blues" )
p.set_array(colors)

ax.add_collection(p)

plt.show()

给我:rings

  1. 我想知道为什么右边有这条水平线,这让我相信我不明白我的代码做了什么。
  2. 它没有成功,因为所有环段都具有相同的颜色,而不是具有不同的阴影。

我以为 p.set_array(颜色) 会像我在 example 中找到的那样发挥作用 尽管我不知道 set_array() 在文档中做了什么 不会放弃太多。

如果有完全不同的方法,请随时告诉我。

最佳答案

您需要将圆从最大到最小相加,这样它们就不会相互重叠。

我用了plot a circle with pyplothttp://matplotlib.org/users/colormaps.html

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm

r = np.arange(1, 0, -0.1)

fig, ax = plt.subplots(1)
ax.set_xlim([-1.1, 1.1])
ax.set_ylim([-1.1, 1.1])

color_vec = np.array([0.9, 0.8, 0.1, 0.1, 0.1, 0.4, 0.2, 0.8, 0.1, 0.9])
colors = cm.get_cmap("Blues")(color_vec)

for i, radius in enumerate(r):
    circle = plt.Circle((0, 0), radius, color=colors[i])
    ax.add_artist(circle)

plt.show()

如果你需要补丁:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection

r = np.arange(1, 0, -0.1)

fig, ax = plt.subplots(1)
ax.set_xlim([-1.1, 1.1])
ax.set_ylim([-1.1, 1.1])
patches = []

colors = np.array([0.9, 0.8, 0.1, 0.1, 0.1, 0.4, 0.2, 0.8, 0.1, 0.9])

phi = np.linspace(0, 2*np.pi, 200)
for radius in r:
    x = radius * np.cos(phi)
    y = radius * np.sin(phi)
    points = np.vstack([x, y]).T
    polygon = Polygon(points, False)
    patches.append(polygon)

p = PatchCollection(patches, cmap="Blues")
p.set_array(colors)

ax.add_collection(p)

plt.show()

关于python - 根据函数绘制 PatchCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39195553/

相关文章:

python - TFLearn CovNet 示例导致使用 CIFAR-10 时出现错误

python - Matplotlib 1.3.0,图例行和文本不匹配

python - "TypeError: Image data can not convert to float"在 python27 中使用 matplotlib

r - 相对于R中的数字向量绘制字符向量

从日志中复制表格和绘图

c# - OxyPlot 在 PlotView/PlotModel 中被点击位置

python - 替换字符之间的点

python - Pandas中水平条形图的修改

python - 使用 matplotlib 中的 show() 和 close()

python - 如何从 C 代码访问 python bool 变量?