在python matplotlib中用多种颜色填充多边形 [英] Fill polygons with multiple colors in python matplotlib

查看:176
本文介绍了在python matplotlib中用多种颜色填充多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib绘制多边形补丁,并想表示每个多边形要用特定颜色填充的部分,即制作饼形图,但为三角形,正方形或六边形.有没有办法改变饼图的形状或为多边形表示多种填充颜色?

I am using matplotlib to plot polygon patches and would like to denote sections of each polygon to be filled with a particular color, i.e. make a pie chart but triangle or square or hexagonal shaped. Is there a way to change the shape of a pie chart or denote multiple fill colors for polygons?

谢谢!

更新:这是我意思的模拟:

Update: Here is mock up of what I mean:

推荐答案

您可以创建 Matplotlib集合,然后传递颜色数组/列表以用于绘图.

You can create a Matplotlib collection, and then pass a array/list of colors to use for plotting.

考虑以下示例.首先得到一些虚拟形状.

Consider the following example. First get some dummy-shapes.

import matplotlib.path as mpath
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

def get_tri(xoff=0, yoff=0, up=1):

    verts = [(0.0 + xoff, 0.0 + yoff),
             (0.5 + xoff, 1.0 * up + yoff),
             (1.0 + xoff, 0.0 + yoff),
             (0.0 + xoff, 0.0 + yoff)]

    p = mpath.Path(verts, [mpath.Path.MOVETO] + (len(verts)-1)*[mpath.Path.LINETO])

    return p

shapes = [get_tri(xoff=x, yoff=y, up=o) for x,y,o in [(0.0, 0,  1),
                                                    (1.0, 0,  1),
                                                    (0.5, 1,  1),
                                                    (0.5, 1, -1)]]

从颜色图中获取颜色:

cmap = plt.cm.RdYlBu_r
colors = cmap(np.linspace(0,1, len(shapes)))

并绘制形状:

fig, ax = plt.subplots(subplot_kw={'aspect': 1.0})

coll = mpl.collections.PathCollection(shapes, facecolor=colors, linewidth=3)

ax.add_collection(coll)
ax.autoscale_view()

请注意,由于我为形状使用了 Paths ,因此我也使用了 PathCollection .如果您使用 Polygons(或其他东西),您还应该使用适当类型的集合,例如 PolyCollection.

Note that since I'm using Paths for my shapes, I'm also using a PathCollection. If you use Polygons (or something else) you should also use the appropriate type of collection, like a PolyCollection.

因此,绘制不同的颜色非常容易,棘手的部分可能是获取路径/多边形.如果已经有了它们,则可以将它们放在列表中以创建集合.

So the plotting of different colors is very easy, the tricky part is probably to get the Paths/Polygons. If you already have them, you can put them in a list to create the collection.

这篇关于在python matplotlib中用多种颜色填充多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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