如何根据Matplotlib中的变量填充颜色的多边形?

时间:2015-08-21 13:24:26

标签: python matplotlib plot

我一直在使用一个shapefile,它具有几个建筑物顶点的x和y坐标,我使用Matplotlib将它们绘制为多边形。但是,我想根据每个建筑物的楼层数量,用红色/灰色/或任何其他颜色填充这些多边形。例如,最小楼层数为零,因此所有楼层为零的建筑物颜色都非常浅。另一方面,最大楼层数为100,所以所有楼层都有100个楼层,非常暗,而且在0到100之间,随着楼层数量的增加,多边形会越来越暗。

我在网上发现了一些东西,但没有具体解决这个问题。我是Python的新手,所以也许我只是不知道能够做我需要的合适的库。

我现在的代码是:(它只绘制多边形,没有填充)

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

i = 0
sf = shapefile.Reader('shapefile')
sr = sf.shapeRecords()
max = 10


while i < max:
    sr_obj = sr[i]
    sr_points = np.array(sr_obj.shape.points)
    records = sf.record(i)
    numfloors = records[42]
    x = sr_points[:,0]
    y = sr_points[:,1]
    sr_plot = zip(*sr_points)
    plt.plot(*sr_plot)
    i = i + 1

plt.show() 

谢谢!

2 个答案:

答案 0 :(得分:9)

您可以使用PatchCollection执行此操作,并使用cmap根据楼层数设置颜色。

例如:

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

fig,ax = plt.subplots(1)

N = 10
nfloors = np.random.rand(N) # some random data

patches = []

cmap = plt.get_cmap('RdYlBu')
colors = cmap(nfloors) # convert nfloors to colors that we can use later

for i in range(N):
    verts = np.random.rand(3,2)+i # random triangles, plus i to offset them
    polygon = Polygon(verts,closed=True)
    patches.append(polygon)

collection = PatchCollection(patches)

ax.add_collection(collection)

collection.set_color(colors)

ax.autoscale_view()
plt.show()

enter image description here

答案 1 :(得分:1)

Matplotlib能够绘制包含polygons的任意形状。

from matplotlib.patches import Polygon
import matplotlib.pyplot as plt

plt.figure()
axes = plt.gca()
axes.add_patch(Polygon([(0, 0), (1, 0.2), (0.3, 0.4), (0.2, 1)],
                       closed=True, facecolor='red'))

添加任意数量的内容。

相关问题