Динамически l oop через годы в Matplotlib Basemap - PullRequest
0 голосов
/ 03 мая 2020

У меня есть этот код, который является слегка измененной версией this :

import time

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import slug

from geonamescache import GeonamesCache
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from matplotlib.widgets import Slider
from mpl_toolkits.basemap import Basemap

filename = 'csv/API_AG.LND.FRST.ZS_DS2_en_csv_v2_988532/API_AG.LND.FRST.ZS_DS2_en_csv_v2_988532.csv'
shapefile = 'shapes/countries/countries/ne_10m_admin_0_countries_lakes'
num_colors = 9

title = f'Forest area as percentage of land area in'
imgfile = f'img{slug.slug(title)}.png'

description = '''
Forest area is land under natural or planted strands of trees of at least 5 meters in situ,
whether productive or not, and excludes tree strands in agricultural production systems(for example,
in fruit plantations and agroforestry systems) and trees in urban parks and gardens. Countries without
data are shown in grey.
Data: World Bank - worldbank.org | Author: Ramiro Gómez - ramiro.org
'''.strip()

gc = GeonamesCache()
iso3_codes = list(gc.get_dataset_by_key(gc.get_countries(), 'iso3').keys())

df = pd.read_csv(filename, skiprows=4)

df.set_index('Country Code', inplace=True)

print(f"DF: {df}")
years = [col for col in df if col.startswith('200')]
for year in years:

    df.reindex(index=iso3_codes).dropna()  # filter out non-countries and missing values
    print(f"year_col: {year}")
    values = df[year]
    cm = plt.get_cmap('Greens')
    scheme = [cm(i / num_colors) for i in range(num_colors)]
    bins = np.linspace(values.min(), values.max(), num_colors)
    df['bin'] = np.digitize(values, bins) - 1
    df.sort_values('bin', ascending=False).head(10)

    df['bin'] = np.digitize(values, bins) - 1
    df.sort_values('bin', ascending=False).head(10)

    print(f"Style {mpl.style.available}")
    fig = plt.figure(figsize=(11, 6))

    ax = fig.add_subplot(111, facecolor='w', frame_on=False)
    fig.canvas.set_window_title(f'Forest area as percentage of land area in {year}')
    fig.suptitle(f'Forest area as percentage of land area in {year}', fontsize=30, y=0.95)

    m = Basemap(lon_0=0, projection='robin')
    m.drawmapboundary(color='w')

    m.readshapefile(shapefile, 'units', color='#444444', linewidth=0.2)
    for info, shape in zip(m.units_info, m.units):
        iso3 = info['ADM0_A3']
        if iso3 not in df.index:
            color = '#dddddd'
        else:
            color = scheme[df.loc[iso3]['bin']]

        patches = [Polygon(np.array(shape), True)]
        pc = PatchCollection(patches)
        pc._set_facecolor(color)
        ax.add_collection(pc)

    # Cover up Antarctica so legend can be placed over it
    ax.axhspan(0, 1000 * 1800, facecolor='w', edgecolor='w', zorder=2)

    # Draw color legend
    ax_legend = fig.add_axes([0.35, 0.14, 0.3, 0.03], zorder=3)
    cmap = mpl.colors.ListedColormap(scheme)
    cb = mpl.colorbar.ColorbarBase(ax_legend, cmap=cmap, ticks=bins, boundaries=bins, orientation='horizontal')
    cb.ax.set_xticklabels([str(round(i, 1)) for i in bins])

    # Set the map footer
    plt.annotate(description, xy=(-0.8, -6.2), size=12, xycoords='axes fraction')
plt.show()
plt.close()

Это открывает окно графика для каждого года с 2000 по 2009 год. Я хотел бы изменить это так, чтобы открылось одно окно, и оно перебирает каждый год, обновляя данные соответственно. Как это сделать?

...