matplotlib.patches.Polygon 颜色未渲染

matplotlib.patches.Polygon colors not rendering

for info, shape in zip(map.counties_info, map.counties):
    if info['FIPS'] in geoids:
        x = np.random.rand(1)[0]
        c = cmap(x)[:3]
        newc = rgb2hex(c)
        patches.append(Polygon(np.array(shape), color=newc, closed=True))

ax.add_collection(PatchCollection(patches))

plt.title('Counties with HQ of NYSE-Listed Firms: 1970')
plt.show()

生成此图像:

我的问题是代码专门要求多边形中的随机颜色。如果我打印 newc 的值并将它们显示在将十六进制代码转换为颜色的网站上,则会有多种不同的颜色。但是输出只有一个。我该如何解决这个问题?

为了使 PatchCollection 的各个色块具有不同的颜色,您有两种选择。

  1. 使用原始补丁的颜色。​​
  2. 使用颜色图根据一些值数组确定颜色。

使用原始补丁的颜色。​​

这种方法最接近问题中的代码。需要将参数 match_original=True 设置为补丁集合。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
import matplotlib.patches
import matplotlib.collections

ar = np.array([[0,0],[1,0],[1,1],[0,1],[0,0]])
cmap=plt.cm.jet
patches=[]

fig, ax=plt.subplots()

for i in range(5):
    x = np.random.rand(1)[0]
    c = cmap(x)[:3]
    poly = plt.Polygon(ar+i, color=c, closed=True)
    patches.append(poly)

collection = matplotlib.collections.PatchCollection(patches,match_original=True)
ax.add_collection(collection)

ax.autoscale()
plt.show()

使用颜色图根据一些值数组确定颜色。

这可能更容易实现。您可以将值数组设置为 PatchCollection 并指定多边形根据其着色的颜色图,而不是为每个单独的多边形指定颜色。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
import matplotlib.patches
import matplotlib.collections

ar = np.array([[0,0],[1,0],[1,1],[0,1],[0,0]])
values = np.random.rand(5)
cmap=plt.cm.jet
patches=[]

fig, ax=plt.subplots()

for i in range(len(values)):
    poly = plt.Polygon(ar+i, closed=True)
    patches.append(poly)

collection = matplotlib.collections.PatchCollection(patches, cmap=cmap)
collection.set_array(values)
ax.add_collection(collection)
ax.autoscale()

plt.show()