[Python] How to create a Plotly animation from a list of figure objects?

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list of Plotly figures and I want to create an animation that iterates over each figure on a button press. Similar the examples found on Intro to Animations in Python. I pretty much tried re-creating several of the examples on the page with no luck.

    It seems like there should be a simple solution but I have not been able to find one. I should note that I do not want to animate the geocoded cities but rather the weather layout - i.e., mapbox_layers

    Below is the code to create the list of figures:

    import requests
    from bs4 import BeautifulSoup
    import pandas as pd
    import plotly.express as px

    # just some geocoded data from plotly
    us_cities = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
    # GET request to pull the datetime info
    r = requests.get('https://geo.weather.gc.ca/geomet?service=WMS&version=1.3.0&request=GetCapabilities&layer=GDPS.DIAG_NW_PT1H')
    # create the soup
    soup = BeautifulSoup(r.text, 'xml')
    # start and end dates in UTC
    start, end = soup.findAll('Dimension')[0].text.split('/')[:2]
    # create a date range
    dates = pd.date_range(start, end, freq='1h').strftime('%Y-%m-%dT%H:%M:%SZ')[0::3]
    # iterate over the dates to create the figures
    figs = []
    for date in dates:
    fig = px.scatter_mapbox(us_cities, lat="lat", lon="lon", hover_name="City", hover_data=["State", "Population"],
    color_discrete_sequence=["black"], zoom=3, height=600, center={'lat': 42.18845, 'lon':-87.81544},
    title=date)

    fig.update_layout(
    mapbox_style="open-street-map",
    mapbox_layers=[
    {
    "below": 'traces',
    "sourcetype": "raster",
    "sourceattribution": "Government of Canada",
    "source": ["https://geo.weather.gc.ca/geomet/?"
    "SERVICE=WMS&VERSION=1.3.0"
    "&REQUEST=GetMap"
    "&BBOX={bbox-epsg-3857}"
    "&CRS=EPSG:3857"
    "&WIDTH=1000"
    "&HEIGHT=1000"
    "&LAYERS=GDPS.DIAG_NW_PT1H"
    "&TILED=true"
    "&FORMAT=image/png"
    f"&TIME={date}"
    ],
    },
    ]
    )

    fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})
    figs.append(fig)


    figs[0] [​IMG]

    figs[6] [​IMG]

    figs[12] [​IMG]

    Continue reading...

Compartilhe esta Página