我正在尝试编写一个 python 程序,它显示世界地图的动画,其中国家根据可再生能源的使用量来改变颜色。我试图让它显示 1960 年所有国家的颜色,然后是 1961 年所有国家的颜色,然后是 1962 年......
我正在使用 cartopy 将国家/地区添加到图中,并根据我从 SQL 数据库中提取到 pandas 数据框中的值来确定它们的颜色。我能够让地图显示我想要的一年,如下所示:
但是,我无法弄清楚如何对其进行动画处理。我尝试使用 FuncAnimate,但我真的很难理解它是如何工作的。所有的例子似乎都有返回线条的函数,但我没有绘制线条或轮廓。这是我尝试过的:
import sqlite3
import pandas as pd
import os
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation as animation
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
from math import log
from math import exp
from matplotlib import colors
path = 'H:/USER/DVanLunen/indicator_data/world-development-indicators/'
os.chdir(path)
con = sqlite3.connect('database.sqlite')
# Grab :
# % of electricity from renewable sources EG.ELC.RNWX.ZS
# 1960 - 2013
Indicator_df = pd.read_sql('SELECT * '
'FROM Indicators '
'WHERE IndicatorCode in('
'"EG.ELC.RNWX.ZS"'
')'
, con)
# setup colorbar stuff and shape files
norm = mpl.colors.Normalize(vmin=0, vmax=30)
colors_in_map = []
for i in range(30):
val = log(i + 1, logbase) / log(31, logbase)
colors_in_map.append((1 - val, val, 0))
cmap = colors.ListedColormap(colors_in_map)
shpfilename = shpreader.natural_earth(resolution='110m',
category='cultural',
name='admin_0_countries')
reader = shpreader.Reader(shpfilename)
countries_map = reader.records()
logbase = exp(1)
fig, ax = plt.subplots(figsize=(12, 6),
subplot_kw={'projection': ccrs.PlateCarree()})
def run(data):
"""Update the Dist"""
year = 1960 + data % 54
logbase = exp(1)
for n, country in enumerate(countries_map):
facecolor = 'gray'
edgecolor = 'black'
indval = Indicator_df.loc[(Indicator_df['CountryName'] ==
country.attributes['name_long']) &
(Indicator_df['Year'] == year), 'Value']
if indval.any():
greenamount = (log(float(indval) + 1, logbase) /
log(31, logbase))
facecolor = 1 - greenamount, greenamount, 0
ax.add_geometries(country.geometry, ccrs.PlateCarree(),
facecolor=facecolor, edgecolor=edgecolor)
ax.set_title('Percent of Electricity from Renewable Sources ' +
str(year))
ax.figure.canvas.draw()
cax = fig.add_axes([0.92, 0.2, 0.02, 0.6])
cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm,
spacing='proportional')
cb.set_label('%')
ani = animation.FuncAnimation(fig, run, interval=200, blit=False)
plt.show()
任何帮助将不胜感激。谢谢!
Indicator_df 的一些示例数据(不是真实的):
CountryName Year Value
United States 1960 5
United States 1961 10
United States 1962 20
United States 1963 30