matplotlib 如何将绘图转换为NumPy?

v1uwarro  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(182)

我想保存一个绘图(通过代码构建的多边形)到NumPy(不是作为图像文件),但我不知道如何才能做到这一点?!
这是我代码:

fig, ax = plt.subplots(figsize=(5.12, 5.12))
N = 3
val = np.random.rand(N, 2, 3)
patches = []
for i in range(3):
    patches.append(Polygon(val[:, :, i], True))
p = PatchCollection(patches, alpha=0.6)
p.set_array(np.array([500,23,1002]))  # assign values
ax.add_collection(p)
fig.colorbar(p)
plt.axis('off')
plt.show()

和绘制:a plot after run above code
谁能告诉我,我该怎么做?

lmyy7pcs

lmyy7pcs1#

如果你想保存多边形,你只需要记住每个多边形的顶点。对于每个形状和顶点集,最好保存为字典,因为这些是.json文件要处理的对象的特征。
docs中,Polygon()有一个方法可以检索多边形.get_xy()的顶点,因此我们可以使用它来获取每个顶点的坐标元组。
接下来你要做的是保存ax.add_collection中插入的数组所指定的每个三角形中的值,我们可以把它移到代码的顶部,然后遍历值列表,把它们作为键字典中的值添加进去。
然后代码变为:

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

import json # To save the dictionary format

fig, ax = plt.subplots(figsize=(5.12, 5.12))

N = 3
val = np.random.rand(N, 2, 3)
fill = [500,23,1002] # The fill values you want to save
patches = []         # The list to save each triangle object
keys = 'tri'         # The names of each triangle
tri_dict = {}        # Initialize the final dictionary

for i in range(3):
    poly = Polygon(val[:, :, i], True)
    vert = poly.get_xy() # Get the vertices for the Polygon
    patches.append(poly) 
    
    my_dict = { # Create a dictionary of chartacteristics for a single triangle
        'vertices':vert.tolist(),
        'fill': fill[i]
        }
    tri_dict[keys+f'{i}'] = my_dict # For the tiangle name as the key, 
                                    # assign the corresponding values

# print(tri_dict) # To show that you are saving the information of each triangle within 
                  # a dictionary of dictionaries

# Saving the dictionary as .json
jsonString = json.dumps(tri_dict, indent=4)
jsonFile = open(r"<YOUR PATH HERE>\\"+"data.json", "w")
jsonFile.write(jsonString)
jsonFile.close()

# Plot the resulting triangles
p = PatchCollection(patches, alpha=0.6)
p.set_array(fill) 
ax.add_collection(p)
fig.colorbar(p)
plt.axis('off')
plt.show()

从这里开始,您应该能够根据您的用例来使用该结构,但是对于所提出的问题,这应该足够了。希望这对您有所帮助!

相关问题