python机器学习使数据更鲜活的可视化工具Pandas_Alive
作者:Python学习与数据挖掘 发布时间:2022-09-26 04:57:12
标签:机器学习,Pandas,Alives,数据可视化
数据动画可视化制作在日常工作中是非常实用的一项技能。目前支持动画可视化的库主要以Matplotlib-Animation为主,其特点为:配置复杂,保存动图容易报错。
安装方法
pip install pandas_alive # 或者
conda install pandas_alive -c conda-forge
使用说明
pandas_alive 的设计灵感来自 bar_chart_race,为方便快速进行动画可视化制作,在数据的格式上需要满足如下条件:
每行表示单个时间段
每列包含特定类别的值
索引包含时间组件(可选)
支持示例展示
水平条形图
import pandas_alive
covid_df = pandas_alive.load_dataset()
covid_df.plot_animated(filename='examples/perpendicular-example.gif',perpendicular_bar_func='mean')
垂直条形图比赛
import pandas_alive
covid_df = pandas_alive.load_dataset()
covid_df.plot_animated(filename='examples/example-barv-chart.gif',orientation='v')
条形图
与时间与 x 轴一起显示的折线图类似
import pandas_alive
covid_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':0.1,'y':0.9},
enable_progress_bar=True, steps_per_period=2, interpolate_period=True, period_length=200
)
饼图
import pandas_alive
covid_df = pandas_alive.load_dataset()
covid_df.plot_animated(filename='examples/example-pie-chart.gif',kind="pie",rotatelabels=True,period_label={'x':0,'y':0})
多边形地理空间图
import geopandas
import pandas_alive
import contextily
gdf = geopandas.read_file('data/italy-covid-region.gpkg')
gdf.index = gdf.region
gdf = gdf.drop('region',axis=1)
map_chart = gdf.plot_animated(filename='examples/example-geo-polygon-chart.gif',basemap_format={'source':contextily.providers.Stamen.Terrain})
多个图表
pandas_alive 支持单个可视化中的多个动画图表。
示例1
import pandas_alive
urban_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(n_visible=10,title='Top 10 Populous Countries',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)
示例2
import pandas_alive
covid_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)
示例3
import pandas_alive
import pandas as pd
data_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].values
data = data.fillna(method="pad")
data = data.fillna(0)
data = data.set_index("Year").loc[1900:].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
)
示例4
import geopandas
import pandas as pd
import pandas_alive
import contextily
import matplotlib.pyplot as plt
import urllib.request, json
with 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 component
covid_nsw_data_url = data["result"]["resources"][0]["url"]
# Read csv from data API url
nsw_covid = pd.read_csv(covid_nsw_data_url)
postcode_dataset = pd.read_csv("data/postcode-data.csv")
# Prepare data from NSW health dataset
nsw_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 matching
grouped_df = grouped_df.T
postcode_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 chart
grouped_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 geopackage
gdf = gdf.drop(['Longitude','Latitude'],axis=1)
gdf.columns = gdf.columns.astype(str)
gdf['postcode'] = gdf.index
gdf.to_file("data/nsw-covid19-cases-by-postcode.gpkg", layer='nsw-postcode-covid', driver="GPKG")
# Prepare GeoDataFrame for plotting
gdf.index = gdf.postcode
gdf = gdf.drop('postcode',axis=1)
gdf = gdf.to_crs("EPSG:3857") #Web Mercator
map_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 datetime
bar_chart = cases_df.sum(axis=1).plot_animated(
kind='line',
label_events={
'Ruby Princess Disembark':datetime.strptime("19/03/2020", "%d/%m/%Y"),
'Lockdown':datetime.strptime("31/03/2020", "%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': .85, 'y': .2, 's': s, '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 time
timestr = time.strftime("%d/%m/%Y")
plots = [bar_chart, line_chart, map_chart, race_chart]
from matplotlib import rcParams
rcParams.update({"figure.autolayout": False})
# make sure figures are `Figure()` instances
figs = 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_ax1
f3_ax2 = figs.add_subplot(gs[1, 0])
f3_ax2.set_title(line_chart.title)
line_chart.ax = f3_ax2
f3_ax3 = figs.add_subplot(gs[1, 1])
f3_ax3.set_title(map_chart.title)
map_chart.ax = f3_ax3
f3_ax4 = figs.add_subplot(gs[1, 2])
f3_ax4.set_title(race_chart.title)
race_chart.ax = f3_ax4
timestr = 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
)
来源:https://blog.csdn.net/weixin_38037405/article/details/109426609


猜你喜欢
- this 的定义表示当前执行代码的环境对象 因此可将 this 的剖析分为“全局环境” 和 “函数环境” 两种类型的环境对象全局环
- 报错一$ php artisan migrateIlluminate\Database\QueryException : could not
- 一、字符串离散化示例对于一组电影数据,我们希望统计电影分类情况,应该如何处理数据?(每一个电影都有很多个分类)思路:首先构造一个全为0的数组
- 前言只统计像素的灰度值这一特征,可将其成为一维直方图。二维直方图可以统计像素的色相和饱和度,用于查找图像的颜色直方图。一、OpenCV中的二
- 报“服务没有及时响应或控制请求”的错误,改用pyinstaller生成也是不行;查资料后修改setup.py如下即可,服务名、脚本名请自行替
- 对于初学者,入门至关重要,这关系到初学者是从入门到精通还是从入门到放弃。以下是结合Python的学习经验,整理出的一条学习路径,主要有四个阶
- 经常在前端面试或是和其他同行沟通是,在谈到构造在JS定义构造函数的方法是最好使用原型的方式:将方法定义到构造方法的prototype上,这样
- 一、默认参数python为了简化函数的调用,提供了默认参数机制:这样在调用pow函数时,就可以省略最后一个参数不写:在定义有默认参数的函数时
- 当今越来越多的应用程序迁移到web平台上。由于没有平台的限制和安装的要求,SAAS的模式看起来非常有吸引力。Web应用程序的界面设计,其核心
- golang支持两种随机数生成方式:math/rand // 伪随机cr
- Python 中要创建对象列表:声明一个新变量并将其初始化为一个空列表。使用 for 循环迭代范围对象。实例化一个类以在每次迭代时创建一个对
- 安装docker桌面程序从docker官网下载并安装桌面程序。安装好后启动桌面程序。若出现以下错误,说明你的docker 没有启动。1. d
- 1. requests发送文件功能Requests 使得上传多部分编码文件变得很简单url = 'http://httpbin.or
- 前言模块在其自身的作用域里执行,而不是在全局作用域里;这意味着定义在一个模块里的变量,函数,类等等在模块外部是不可见的,除非你明确地使用ex
- 1.今天网上下载一个博客项目,发现本地访问,js,css加载不了.我想应该是项目上线的安全措施,但是我想调试项目.找到方法如下在settin
- 实际效果:假设给定目录"/media/data/programmer/project/python" ,备份路径&quo
- asp三天学好ADO对象之第二天 今天来说一下Recordset对象的一些方法。1、AddNew 方法创建可更新 Recordset 对象的
- 前言本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。PS:如有需要Python学习资料的
- 大家都知道在Dreamwerver中可以很方便地实现记录集的分页显示,但是生成的代码的确很庞大,影响了网页的显示速度,看起来条理也不是很清晰
- uwsgi介绍uWSGI是一个Web服务器,它实现了WSGI协议、uwsgi、http等协议。Nginx中HttpUwsgiModule的作