Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use python's visualization tool Pandas_Alive

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use python's visualization tool Pandas_Alive". In daily operation, I believe many people have doubts about how to use python's visualization tool Pandas_Alive. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to use python's visualization tool Pandas_Alive". Next, please follow the editor to study!

Data animation visualization is a very practical skill in daily work. At present, the library that supports animation visualization is mainly based on Matplotlib-Animation, which is characterized by complex configuration and easy to report errors when saving dynamic images.

Installation method pip install pandas_alive # or conda install pandas_alive-c conda-forge instructions

The design of pandas_alive is inspired by bar_chart_race. In order to facilitate the visualization of animation, the following conditions need to be met in terms of data format:

Each line represents a single time period

Each column contains values for a specific category

The index contains time components (optional)

Support example display horizontal bar chart import pandas_alivecovid_df = pandas_alive.load_dataset () covid_df.plot_animated (filename='examples/perpendicular-example.gif',perpendicular_bar_func='mean') vertical bar chart competition import pandas_alivecovid_df = pandas_alive.load_dataset () covid_df.plot_animated (filename='examples/example-barv-chart.gif',orientation='v') bar chart

Similar to a line chart displayed with time and x-axis

Import pandas_alivecovid_df = pandas_alive.load_dataset () covid_df.sum (axis=1) .fillna (0). Plot_animated (filename='examples/example-bar-chart.gif',kind='bar', period_label= {'x covid_df.sum 0.1) enable_progress_bar=True, steps_per_period=2, interpolate_period=True Period_length=200) Pie chart import pandas_alivecovid_df = pandas_alive.load_dataset () covid_df.plot_animated (filename='examples/example-pie-chart.gif',kind= "pie", rotatelabels=True,period_label= {'x the Velcro 0coverywise Vega 0}) Polygon geospatial map import geopandasimport pandas_aliveimport contextilygdf = geopandas.read_file ('data/italy-covid-region.gpkg') gdf.index = gdf.regiongdf = gdf.drop (' region') Axis=1) map_chart = gdf.plot_animated (filename='examples/example-geo-polygon-chart.gif',basemap_format= {'source':contextily.providers.Stamen.Terrain}) multiple charts

Pandas_alive supports multiple animated charts in a single visualization.

Example 1

Import pandas_aliveurban_df = pandas_alive.load_dataset ("urban_pop") animated_line_chart = (urban_df.sum (axis=1) .pct _ change () .fillna (method='bfill') .mul (100) .plot _ animated (kind= "line", title= "Total% Change in Population", period_label=False,add_legend=False) animated_bar_chart = urban_df.plot_animated Period_fmt= "% Y") pandas_alive.animate_multiple_plots ('examples/example-bar-and-line-urban-chart.gif', [animated_bar_chart,animated_line_chart], title='Urban Population 1977-2018, adjust_subplot_top=0.85, enable_progress_bar=True)

Example 2

Import pandas_alivecovid_df = pandas_alive.load_dataset () animated_line_chart = covid_df.diff () .fillna (0). Plot_animated (kind='line',period_label=False,add_legend=False) animated_bar_chart = covid_df.plot_animated (n_visible=10) pandas_alive.animate_multiple_plots ('examples/example-bar-and-line-chart.gif', [animated_bar_chart,animated_line_chart], enable_progress_bar=True)

Example 3

Import pandas_aliveimport pandas as pddata_raw = pd.read_csv ("https://raw.githubusercontent.com/owid/owid-datasets/master/datasets/Long%20run%20life%20expectancy%20-%20Gapminder%2C%20UN/Long%20run%20life%20expectancy%20-%20Gapminder%2C%20UN.csv")list_G7 = [" Canada "," France "," Germany "," Italy "," Japan "," United Kingdom "," United States ") ] data_raw = data_raw.pivot (index= "Year", columns= "Entity", values= "Life expectancy (Gapminder) UN) ") data = pd.DataFrame () data [" Year "] = data_raw.reset_index () [" Year "] for country in list_G7: data [country] = data_ raw [country] .valuesdata = data.fillna (method=" pad ") data = data.fillna (0) data = data.set_index (" Year "). Local.reset _ index () data [" Year "] = pd.to_datetime (data.reset_index () [" Year ") ] .astype (str) data = data.set_index ("Year") animated_bar_chart = data.plot_animated (period_fmt= "% Y") Perpendicular_bar_func= "mean", period_length=200,fixed_max=True) animated_line_chart = data.plot_animated (kind= "line", period_fmt= "% Y", period_length=200,fixed_max=True) pandas_alive.animate_multiple_plots ("examples/life-expectancy.gif", plots= [animated _ bar_chart, animated_line_chart], title= "Life expectancy in G7 countries up to 2015", adjust_subplot_left=0.2, adjust_subplot_top=0.9, enable_progress_bar=True)

Example 4

Import geopandasimport pandas as pdimport pandas_aliveimport contextilyimport matplotlib.pyplot as pltimport urllib.request Jsonwith urllib.request.urlopen ("https://data.nsw.gov.au/data/api/3/action/package_show?id=aefcde60-3b0c-4bc0-9af1-6fe652944ec2") as url: data = json.loads (url.read (). Decode ()) # Extract url to csv componentcovid_nsw_data_url = data [" result "] [" resources "] [0] [" url "] # Read csv from data API urlnsw_covid = pd.read_csv (covid_nsw_data_) Url) postcode_dataset = pd.read_csv ("data/postcode-data.csv") # Prepare data from NSW health datasetnsw_covid = nsw_covid.fillna (9999) nsw_covid ["postcode"] = nsw_covid ["postcode"] .astype (int) grouped_df = nsw_covid.groupby (["notification_date") "postcode"]. Size () grouped_df = pd.DataFrame (grouped_df). Unstack () grouped_df.columns = grouped_df.columns.droplevel (). Astype (str) grouped_df = grouped_df.fillna (0) grouped_df.index = pd.to_datetime (grouped_df.index) cases_df = grouped_df# Clean data in postcode dataset prior to matchinggrouped_df = grouped_df.Tpostcode_dataset = postcode_ dataset [postcode _ dataset ['Longitude'] .notna ()] Postcode_dataset = postcode_ dataset [postcode _ dataset ['Longitude']! = 0] postcode_dataset = postcode_ dataset [postcode _ dataset [' Latitude'] .notna ()] postcode_dataset = postcode_ dataset [postcode _ dataset ['Latitude']! = 0] postcode_dataset [' Postcode'] = postcode_dataset ['Postcode'] .astype (str) # Build GeoDataFrame from Lat Long dataset and make map chartgrouped_df [' Longitude'] = grouped_df.index.map (postcode_dataset.set_index ( 'Postcode') [' Longitude'] .to_dict () grouped_df ['Latitude'] = grouped_df.index.map (postcode_dataset.set_index (' Postcode') ['Latitude'] .to_dict ()) gdf = geopandas.GeoDataFrame (grouped_df) Geometry=geopandas.points_from_xy (grouped_df.Longitude, grouped_df.Latitude), crs= "EPSG:4326") gdf = gdf.dropna () # Prepare GeoDataFrame for writing to geopackagegdf = gdf.drop (['Longitude','Latitude'], axis=1) gdf.columns = gdf.columns.astype (str) gdf [' postcode'] = gdf.indexgdf.to_file ("data/nsw-covid19-cases-by-postcode.gpkg", layer='nsw-postcode-covid') Driver= "GPKG") # Prepare GeoDataFrame for plottinggdf.index = gdf.postcodegdf = gdf.drop ('postcode',axis=1) gdf = gdf.to_crs ("EPSG:3857") # Web Mercatormap_chart = gdf.plot_animated (basemap_format= {' source':contextily.providers.Stamen.Terrain}, cmap='cool') cases_df.to_csv ('data/nsw-covid-cases-by-postcode.csv') from datetime import datetimebar_chart = cases_df.sum (axis=1). Plot_animated (kind='line') Label_events= {'Ruby Princess Disembark':datetime.strptime ("1931 d/%m/%Y 2020", "% d/%m/%Y"),' Lockdown':datetime.strptime ("31 d/%m/%Y")}, fill_under_line_color= "blue" Add_legend=False) map_chart.ax.set_title ('Cases by Location') grouped_df = pd.read_csv (' data/nsw-covid-cases-by-postcode.csv', index_col=0, parse_dates= [0]) line_chart = (grouped_df.sum (axis=1) .cumsum () .fillna (0) .plot _ animated (kind= "line", period_label=False, title= "Cumulative Total Cases") Add_legend=False)) def current_total (values): total = values.sum () s = f'Total: {int (total)} 'return {' x right',: .85, 'Yee: .2,' ha': 'right',' size': 11} race_chart = grouped_df.cumsum (). Plot_animated (n_visible=5, title= "Cases by Postcode", period_label=False Period_summary_func=current_total) import timetimestr = time.strftime ("% d/%m/%Y") plots = [bar_chart, line_chart, map_chart, race_chart] from matplotlib import rcParamsrcParams.update ({"figure.autolayout": False}) # make sure figures are `Figure () `instancesfigs = plt.Figure () gs = figs.add_gridspec (2,3, hspace=0.5) f3_ax1 = figs.add_subplot (gs [0) :) f3_ax1.set_title (bar_chart.title) bar_chart.ax = f3_ax1f3_ax2 = figs.add_subplot (gs [1,0]) f3_ax2.set_title (line_chart.title) line_chart.ax = f3_ax2f3_ax3 = figs.add_subplot (gs [1,1]) f3_ax3.set_title (map_chart.title) map_chart.ax = f3_ax3f3_ax4 = figs.add_subplot (gs [1) 2]) f3_ax4.set_title (race_chart.title) race_chart.ax = f3_ax4timestr = cases_df.index.max (). Strftime ("% d/%m/%Y") figs.suptitle (f "NSW COVID-19 Confirmed Cases up to {timestr}") pandas_alive.animate_multiple_plots ('examples/nsw-covid.gif', plots, figs, enable_progress_bar=True) so far The study on "how to use python's visualization tool Pandas_Alive" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report