Matplotlib动画直方图颜色图/渐变

时间:2020-10-03 01:43:18

标签: python matplotlib

我正在尝试使用matplotlib为直方图制作动画,并且我想使用颜色图显示不同的条形,例如:

current animated histograms

当我在每一帧清除整个图形然后重画所有内容时,我就可以进行此工作。但这很慢,因此我正在尝试使用matplotlib本身的example

这有效并且非常快,但是很遗憾,我不知道如何指定颜色图,因为它正在使用patch.PathPatch对象现在绘制直方图。我只能使它与每个单独的条使用相同的单色。

如何指定渐变或颜色图以实现上面显示的所需结果?

这是我目前正在使用的一种具有单色的工作动画的示例。

import numpy as np

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation

# Fixing random state for reproducibility
np.random.seed(19680801)

# histogram our data with numpy
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)

# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
nrects = len(left)

nverts = nrects * (1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom

patch = None


def animate(i):
    # simulate new data coming in
    data = np.random.randn(1000)
    n, bins = np.histogram(data, 100)
    top = bottom + n
    verts[1::5, 1] = top
    verts[2::5, 1] = top
    return [patch, ]

fig, ax = plt.subplots()
barpath = path.Path(verts, codes)
patch = patches.PathPatch(
    barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)

ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())

ani = animation.FuncAnimation(fig, animate, 100, repeat=False, blit=True)
plt.show()

1 个答案:

答案 0 :(得分:1)

我建议您使用BarContainer,您可以分别更改条形颜色。在您的示例中,路径是单个对象,matplotlib似乎不支持单个补丁的渐变颜色(虽然不确定)。

import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)

# histogram our data with numpy
data = np.random.randn(1000)
colors = plt.cm.coolwarm(np.linspace(0, 1, 100))

    
def animate(i):
    data = np.random.randn(1000)
    bc = ax.hist(data, 100)[2]
    for i, e in enumerate(bc):
        e.set_color(colors[i])
    return bc

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))

ani = animation.FuncAnimation(fig, animate, 100, repeat=False, blit=True)