matplotlib中的Hexgrid显示意外颜色

时间:2017-12-21 14:31:58

标签: python matplotlib colormap hexagonal-tiles

我一直在尝试在Python的六边形网格上创建一个生命游戏克隆。我设法使用hexbin来显示结果并定期更新它们以创建动画。

每个单元格只能包含值01,并且我使用Greys色彩图将它们显示为黑白图块。但是,在输出中,中心图块显示为灰色而不是黑色,即使该值设置为1(我使用print语句来检查这些图块的值)。

enter image description here

我该如何删除?使用不同的颜色贴图,问题变得更加明显,例如Spectral:在这种情况下甚至出现一些水平线)。我之前使用了几乎相同的代码用于具有矩形网格的相同项目,此问题没有显示出来。

# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.mlab as mlab


n = 20       # number of rows
alive = 1       # value of a cell that is alive
dead = 0        # value of a dead cell
pause = False

x = y = np.arange(0, n, 1.0)
X, Y = np.meshgrid(x, y)
Z = np.zeros((n, n))
Z[10][10] = Z[9][11] = Z[10][11] = Z[9][9] = 1

x = X.ravel()
y = Y.ravel()
z = Z.ravel()

def update(*args):
    if not pause:
        advance()

# this is the main function that advances the animation by one frame (time step)
def advance(*args):
    global Z
    newZ = Z.copy()
    for i in range(n):
        for j in range(n):
            total = (Z[i][(j-1)%n] + Z[i][(j+1)%n] + Z[(i-1)%n][j] + Z[(i+1)%n][j] + Z[(i-1)%n][(j-1)%n] + Z[(i+1)%n][(j-1)%n])

            if Z[i][j] == alive:
                if (total < 2) or (total > 4):
                    newZ[i][j] = dead
            else:
                if total == 2:
                    newZ[i][j] = alive
    Z = newZ
    z = Z.ravel()
    grid = plt.hexbin(x, y, z, gridsize=n, cmap="Spectral")
    return [grid]

fig = plt.figure(figsize=(5, 5))
ax = plt.subplot()
ani = animation.FuncAnimation(fig, update, interval=50)
plt.show()

1 个答案:

答案 0 :(得分:2)

您正在使用方格网格来执行生命游戏算法。然后,您将结果映射到六边形网格上。这意味着一些正方形网格值位于六边形网格的同一单元格中(加起来它的值),而一些六边形网格单元格是空的,因为它们不会碰到任何sqaure网格单元格。

enter image description here

例如,您可以看到,例如以(0.5,2.5)为中心的六边形网格单元格不包括原始方格的任何位置。因此,这个单元格保持空白。

由于生命游戏强烈依赖于网格本身,因此无论如何使用不同的网格都没有意义。因此,只需保持方格 - 或让生命游戏在不同的网格上运行,更改完整的算法以考虑使用中的网格。