Skip to main content
 首页 » 编程设计

python之在 Matplotlib 中绘制字形图

2024年10月25日8duanxz

我正在使用 Matplotlib 绘制一些科学可视化图,热图图(如下图)就足够了。我的代码也是全部用 Python 编写的。

但是,现在我需要展示一个更“精致”的情节,它由字形组成。下图(第二张)显示了一个示例:

在该图像中,绘图的每个点都是一个字形,表示矢量场方向的概率。这个字形被画成一个圆圈,有一个主方向和一个标准偏差。

我想做类似的事情。我的想法是在每个位置绘制类似极坐标直方图的东西,并绘制由极坐标图表组成的图。但是,我认为 Matplotlib 不可能做到这一点;至少我不知道如何做到这一点。由于我的整个代码都是用 Python 编写的,我想知道我是否可以以某种方式支持 Matplotlib,或者我是否应该研究如何使用 OpenGL 或其他 API/libraty 来做到这一点。

谢谢。

请您参考如下方法:

也许有很多这样的东西:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.collections import PatchCollection 
from matplotlib.patches import Wedge, Circle 
from math import degrees, pi 
 
fig, ax = plt.subplots() 
wedges = [] 
circles = [] 
 
for x in np.arange(0, 3.3, .3): 
    for y in np.arange(0, 3.3, .3): 
        theta, phi = np.random.random(2)  # functions of (x,y) in reality 
        for v in (0, pi): 
            wedges.append(Wedge((x, y), 
                            .15, 
                            degrees(v - phi - theta/2), 
                            degrees(v - phi + theta/2), 
                            edgecolor='none'), 
                            ) 
        circles.append(Circle((x, y), 
                             .15, 
                             edgecolor='none')) 
 
 
colors = np.linspace(0, 1, len(circles))  # function of (x,y) in reality 
collection = PatchCollection(circles, cmap=plt.cm.jet, alpha=0.2) 
collection.set_array(np.array(colors)) 
collection.set_edgecolor('none') 
ax.add_collection(collection) 
 
#wedgecolors = list(chain.from_iterable(repeat(i,2) for i in colors)) 
wedgecolors = np.array([colors, colors]).flatten('F') # no itertools 
collection = PatchCollection(wedges, cmap=plt.cm.jet, alpha=1) 
collection.set_array(np.array(wedgecolors)) 
collection.set_edgecolor('none') 
ax.add_collection(collection) 
 
ax.set_xlim(0,3) 
ax.set_ylim(0,3) 
ax.set_aspect('equal') 
plt.show() 

(显然,设置边缘颜色必须在 collection.set_array 调用之后完成(重做?)。)