【问题标题】:How to fill polygons with colors based on a variable in Matplotlib?如何根据 Matplotlib 中的变量用颜色填充多边形?
【发布时间】:2015-08-21 13:24:26
【问题描述】:

我一直在使用具有多个建筑物顶点的 x 和 y 坐标的 shapefile,并且我正在使用 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() 

谢谢!

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    您可以使用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()
    

    【讨论】:

    • 谢谢@tom。我想我在这里的某个地方。我只是看不到代码如何读取每个特定建筑物的楼层数并用相应的颜色绘制多边形...
    【解决方案2】:

    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'))
    

    随意添加。

    【讨论】:

    • 感谢@rodin 的快速回复,但我有一个包含 1000 多座建筑物的文件,并说明每个建筑物的颜色不太实用。不知道有没有办法让Python根据楼层数自动填充颜色?
    • @JosuBatallas 只需使用字典。 floorcols={"1":"red","2":"blue"} 那么如果 nf 是您的楼层数字向量 col=floorcols[str(nf)]
    【解决方案3】:

    只是为了添加到@Marjin van Cliet 的答案,您可以使用字典将楼层编号的向量映射到颜色,显然您还需要在循环中设置数据集的多边形角。

    from matplotlib.patches import Polygon
    import matplotlib.pyplot as plt
    
    nfs=[2,3,1,2,3] # number of floors 
    cols={"1":"red","2":"blue","3":"orange"}
    
    plt.figure()
    axes = plt.gca()
    for nf in nfs:
        axes.add_patch(Polygon([(0, 0), (1, 0.2), (0.3, 0.4), (0.2, 1)],
                           closed=True, facecolor=cols[str(nf)]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多