如何根据 Matplotlib 中的变量用颜色填充多边形? [英] How to fill polygons with colors based on a variable in Matplotlib?

查看:44
本文介绍了如何根据 Matplotlib 中的变量用颜色填充多边形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been working with a shapefile that has the x and y coordinates of the vertices of several buildings, and I am using Matplotlib to plot them as polygons. However, I would like to fill these polygons with shades of red/grey/or any other color based on the number of floors each building has. For example, the minimum number of floors is zero, so all buildings with zero floors would be of very light color. On the other hand, the maximum number of floors is 100, so all buildings with a hundred floors would plot very dark, and between 0 and 100 the polygons would plot darker and darker as the number of floors increased.

我在网上找到了一些东西,但没有专门解决这个问题.我是 Python 新手,所以也许我只是不知道可以满足我需要的正确库.

I found a few things online but nothing that tackles this specifically. I am new at Python so maybe I am just not aware of the right library that can do what I need.

我现在的代码是这样的:(它仅绘制多边形,不填充)

My code for now is this: (It plots the polygons only, no fill)

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

谢谢!

推荐答案

您可以使用 PatchCollection 进行此操作,并使用 cmap根据楼层数设置颜色代码>.

You can do this with a PatchCollection, and set the colors according to the number of floors using a 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()

这篇关于如何根据 Matplotlib 中的变量用颜色填充多边形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆