Как добавить цветовую шкалу в сюжет геопанды с анимацией matplotlib - PullRequest
0 голосов
/ 11 марта 2019

Я пытаюсь оживить сюжет геопанды, используя FuncAnimation. По сути, eu_private_map является геопандасом.geodataframe.GeoDataFrame и среди других полей содержит несколько столбцов со значениями параметра x в разных государствах ЕС в течение 10 лет подряд. В каждом столбце указаны значения х за один год.

from matplotlib.animation import FuncAnimation
from IPython.display import HTML
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig = plt.figure() 
ax1 = fig.add_subplot(1,1,1)

def animate(year):
        ax1.clear()
        my_map = eu_private_map.plot(ax=ax1, column=year, vmin=0, vmax=30, legend=False)
        divider = make_axes_locatable(ax1)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(my_map, cax=cax)

# the FuncAnimation function iterates through our animate function using the steps array
years = eu_private.columns.drop('country').tolist()
ani = FuncAnimation(fig, animate, years, interval=1000, blit=False)

HTML(ani.to_jshtml())

Цветная полоса доставляет мне неприятности. С одной стороны, если я устанавливаю legend = True, мне не нравится тот факт, что он не имеет такой же размер (см. Рисунок), как на рисунке, и это создает странный эффект (см. Рисунок). Я попытался this , но получил ошибку: AttributeError: объект 'AxesSubplot' не имеет атрибута 'autoscale_None'. Однако я не могу определить проблему в коде, какую-либо помощь, чтобы исправить обе проблемы одновременно? Большое спасибо

enter image description here enter image description here

1 Ответ

0 голосов
/ 12 марта 2019

Перепробовав множество способов, которые не сработали для геопанд и анимации, я в итоге нашел решение, позволяющее заставить его работать - основная идея отделить цветную полосу от функции анимации и функции инициализации графика.

from matplotlib.animation import FuncAnimation
from IPython.display import HTML
from mpl_toolkits.axes_grid1 import make_axes_locatable


fig = plt.figure(figsize=(20,10)) 
ax1 = fig.add_subplot(1,1,1)

def animate(year):
        ax1.clear()
        eu_private_map.plot(color='gainsboro', ax=ax1, linewidth=0.6, edgecolor='1')
        sm = eu_private_map.dropna().plot(ax=ax1, column=year, vmin=0, vmax=30, cmap = 'viridis',
                                              legend=False, linewidth=0.6, edgecolor='1')
        ax1.set_title(year, fontdict={'fontsize': '23'})
        ax1.axis('off')

def init():
    # Create colorbar as a legend
    sm = plt.cm.ScalarMappable(cmap='viridis', norm=plt.Normalize(vmin=0, vmax=30))
    # empty array for the data range
    sm._A = []
    # add the colorbar to the figure

    divider = make_axes_locatable(ax1)
    cax = divider.append_axes("right", size="5%", pad=0.5)


    cbar = fig.colorbar(sm, cax=cax)
    cbar.ax.tick_params(labelsize=14) 


# the FuncAnimation function iterates through our animate function using the steps array
years = eu_private.columns.drop('country').tolist()[::-1]
ani = FuncAnimation(fig, animate, years, interval=1000, blit=False, init_func=init)

HTML(ani.to_jshtml())
...