Python Matplotlib - imshow但有六边形

问题描述 投票:0回答:1

代码是:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

example_data = np.random.randint(4, size=(40,44))
cmap = colors.ListedColormap(['black', 'green', 'red', 'blue'])
bounds = [0,1,2,3,4]
norm = colors.BoundaryNorm(bounds, cmap.N)

img = plt.imshow(example_data, interpolation = 'nearest', origin = 'lower',
cmap = cmap, norm = norm)

这让我大致得到了我想要的东西。我想要的是,是否有办法让每个瓷砖的形状为六边形而不是方形?我认为imshow可能不是这样做的方法但是如果有一种方法你可以改变默认的瓷砖那就不错了。

谢谢。

python matplotlib imshow
1个回答
-2
投票

谁继续投票,没有评论!我虽然之前的尝试(下面)是一个很好的解决方案。但是,我很欣赏它没有镶嵌得很好,六边形很差。以下是使用补丁的更好解决方案:

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

nx = 40
ny = 44
example_data = np.random.randint(4, size=(nx,ny))
cmap = colors.ListedColormap(['black', 'green', 'red', 'blue'])
bounds = [0,1,2,3,4]
norm = colors.BoundaryNorm(bounds, cmap.N)

x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
X, Y = np.meshgrid(x, y)

dx = np.diff(x)[0]
dy = np.diff(y)[0]
ds = np.sqrt(dx**2 +  dy**2)

patches = []
for i in x:
    for n, j in enumerate(y):
        if n%2:
            polygon = mpatches.RegularPolygon([i-dx/2., j], 6, 0.6*dx)
        else:
            polygon = mpatches.RegularPolygon([i, j], 6, 0.6*dx)
        patches.append(polygon)

collection = PatchCollection(patches, cmap=cmap, norm=norm, alpha=1.0)

fig, ax = plt.subplots(1,1)
ax.add_collection(collection)
collection.set_array(example_data.ravel())
plt.show()

看起来像这样,

enter image description here

以前的方案:

您可以使用带有彩色六边形的散点图,

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

nx = 40
ny = 44
example_data = np.random.randint(4, size=(nx,ny))
cmap = colors.ListedColormap(['black', 'green', 'red', 'blue'])
bounds = [0,1,2,3,4]
norm = colors.BoundaryNorm(bounds, cmap.N)

x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
X, Y = np.meshgrid(x, y)

img = plt.scatter(X.ravel(),Y.ravel(),c=example_data.ravel(), cmap=cmap, norm=norm, s=360, marker=(6, 0), alpha=0.4)

plt.colorbar(img)
plt.show()

看起来像,

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.