You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python制作土耳其恐怖袭击分析动画时文本重叠问题修复求助

解决Basemap动画标题重叠问题

问题原因

每次调用animate函数时,执行plt.axes()会创建新的坐标轴,旧坐标轴未被销毁,导致标题和地图元素反复叠加,出现视觉重叠。

修复步骤及代码

  1. 提前在初始化阶段创建唯一的坐标轴对象
  2. 在animate函数中复用该坐标轴,清除原有内容后再绘制新帧
  3. 让Basemap绑定到固定坐标轴上,避免重复创建绘图区域

修改后的完整代码:

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import matplotlib.animation as animation
import io
import base64
from IPython.display import HTML

# 假设terror_turkey是已加载的目标数据集
fig = plt.figure(figsize=(7,4))
# 提前创建唯一的坐标轴
ax = fig.add_subplot(111)

def animate(Year):
    # 清除坐标轴上的所有内容
    ax.clear()
    ax.set_title('Terrorism In Turkey\n'+ str(Year))
    # 将Basemap绑定到已有的ax上
    m5 = Basemap(projection='lcc', resolution='l', width=1800000, height=900000,
                 lat_0=38.9637, lon_0=35.2433, ax=ax)
    
    # 提取当年数据,避免重复切片
    year_data = terror_turkey[terror_turkey['Year'] == Year]
    lat_gif = year_data['Latitude'].tolist()
    long_gif = year_data['Longitude'].tolist()
    x_gif, y_gif = m5(long_gif, lat_gif)
    
    # 修正原代码的列表推导式语法错误
    sizes = [death + injured for death, injured in zip(year_data['Death'], year_data['Injured'])]
    m5.scatter(x_gif, y_gif, s=sizes, color='r')
    
    m5.drawcoastlines()
    m5.drawcountries()
    m5.fillcontinents(color='coral', lake_color='aqua', zorder=1, alpha=0.4)
    m5.drawmapboundary(fill_color='aqua')

ani = animation.FuncAnimation(fig, animate, frames=terror_turkey.Year.unique(), interval=1500) 

ani.save('animation_tr.gif', writer='imagemagick', fps=1)
plt.close(fig)

filename = 'animation_tr.gif'
video = io.open(filename, 'r+b').read()
encoded = base64.b64encode(video)
HTML(data='''<img src="data:image/gif;base64,{0}" type="gif" />'''.format(encoded.decode('ascii')))

额外优化说明

  • 修正了原代码中列表推导式的语法错误,确保伤亡人数求和逻辑正确
  • 提取年份数据到临时变量,减少重复数据集切片操作,提升代码运行效率
  • 通过ax=ax参数让Basemap固定在同一坐标轴上,彻底避免多图层叠加问题

内容的提问来源于stack exchange,提问作者frkakl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:50:25