本文介绍了Python Seborn热图数据的动态更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态更新用Seborn制作的热图,逐条添加数据行。 下面的示例代码完成了基本工作,但它似乎并没有更新热图,而是在前一个热图中嵌套了一个新的热图。
预先感谢您提供的任何帮助/解决方案。
import numpy as np
np.random.seed(0)
import seaborn as sns
import matplotlib.pyplot as plt
data = np.random.rand(120 ,5900)
data_to_draw = np.zeros(shape=(1,5900))
for i,d in enumerate(data):
# update data to be drawn
data_to_draw = np.vstack((data_to_draw, data[i]))
#keep max 5 rows visible
if data_to_draw.shape[0]>5:
data_to_draw = data_to_draw[1:]
ax = sns.heatmap(data_to_draw,cmap="coolwarm")
plt.draw()
plt.pause(0.1)
推荐答案
我重新构造了您的代码以利用matplotlib.animation.FuncAnimation
。
为了避免在每次迭代中绘制新的热图和柱状图,需要通过seaborn.heatmap
中的ax
和cbar_ax
参数指定在哪个轴上绘制它们。
此外,绘制热图后,使用ax.cla()
可以方便地擦除前一个热图。
完成代码
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
np.random.seed(0)
data = np.random.rand(120, 50)
data_to_draw = np.zeros(shape = (1, 50))
def animate(i):
global data_to_draw
data_to_draw = np.vstack((data_to_draw, data[i]))
if data_to_draw.shape[0] > 5:
data_to_draw = data_to_draw[1:]
ax.cla()
sns.heatmap(ax = ax, data = data_to_draw, cmap = "coolwarm", cbar_ax = cbar_ax)
grid_kws = {'width_ratios': (0.9, 0.05), 'wspace': 0.2}
fig, (ax, cbar_ax) = plt.subplots(1, 2, gridspec_kw = grid_kws, figsize = (10, 8))
ani = FuncAnimation(fig = fig, func = animate, frames = 100, interval = 100)
plt.show()
如果您希望保留原有的代码结构,则可以应用相同的原则:
import numpy as np
np.random.seed(0)
import seaborn as sns
import matplotlib.pyplot as plt
data = np.random.rand(120, 5900)
data_to_draw = np.zeros(shape = (1, 5900))
grid_kws = {'width_ratios': (0.9, 0.05), 'wspace': 0.2}
fig, (ax, cbar_ax) = plt.subplots(1, 2, gridspec_kw = grid_kws, figsize = (10, 8))
for i, d in enumerate(data):
# update data to be drawn
data_to_draw = np.vstack((data_to_draw, data[i]))
# keep max 5 rows visible
if data_to_draw.shape[0] > 5:
data_to_draw = data_to_draw[1:]
sns.heatmap(ax = ax, data = data_to_draw, cmap = "coolwarm", cbar_ax = cbar_ax)
plt.draw()
plt.pause(0.1)
这篇关于Python Seborn热图数据的动态更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!