看完这篇文章,我彻底爱上了Python动态图表!

06 动态饼状图

covid_df = pd.read_csv(‘data/covid19.csv’, index_col=0, parse_dates=[0])

covid_df.plot_animated(filename=‘examples/example-pie-chart.gif’, kind=“pie”,

rotatelabels=True, period_label={‘x’: 0, ‘y’: 0})

07 动态气泡图

multi_index_df = pd.read_csv(“data/multi.csv”, header=[0, 1], index_col=0)

multi_index_df.index = pd.to_datetime(multi_index_df.index, dayfirst=True)

map_chart = multi_index_df.plot_animated(

kind=“bubble”,

filename=“examples/example-bubble-chart.gif”,

x_data_label=“Longitude”,

y_data_label=“Latitude”,

size_data_label=“Cases”,

color_data_label=“Cases”,

vmax=5, steps_per_period=3, interpolate_period=True, period_length=500,

dpi=100

)

08 地理空间点图表

import geopandas

import pandas_alive

import contextily

gdf = geopandas.read_file(‘data/nsw-covid19-cases-by-postcode.gpkg’)

gdf.index = gdf.postcode

gdf = gdf.drop(‘postcode’,axis=1)

result = gdf.iloc[:, :20]

result[‘geometry’] = gdf.iloc[:, -1:][‘geometry’]

map_chart = result.plot_animated(filename=‘examples/example-geo-point-chart.gif’,

basemap_format={‘source’:contextily.providers.Stamen.Terrain})

09 多边形地理图表

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)

result = gdf.iloc[:, :20]

result[‘geometry’] = gdf.iloc[:, -1:][‘geometry’]

map_chart = result.plot_animated(filename=‘examples/example-geo-polygon-chart.gif’,

basemap_format={‘source’: contextily.providers.Stamen.Terrain})

10 多个动态图表

covid_df = pd.read_csv(‘data/covid19.csv’, index_col=0, parse_dates=[0])

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)

11 城市人口

def population():

urban_df = pd.read_csv(“data/urban_pop.csv”, index_col=0, parse_dates=[0])

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)

12 G7国家平均寿命

def life():

data_raw = pd.read_csv(“data/long.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”)

data = data.iloc[:25, :]

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

)

13 新南威尔斯州COVID可视化

def nsw():

import geopandas

import pandas as pd

import pandas_alive

import contextily

import matplotlib.pyplot as plt

import json

with open(‘data/package_show.json’, ‘r’, encoding=‘utf8’)as fp:

data = json.load(fp)

# Extract url to csv component

covid_nsw_data_url = data[“result”][“resources”][0][“url”]

print(covid_nsw_data_url)

# Read csv from data API url

nsw_covid = pd.read_csv(‘data/confirmed_cases_table1_location.csv’)

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

result = gdf.iloc[:, :22]

result[‘geometry’] = gdf.iloc[:, -1:][‘geometry’]

gdf = result

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’)

cases_df = cases_df.iloc[:22, :]

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])

grouped_df = grouped_df.iloc[:22, :]

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

)

14 意大利COVID可视化****

def italy():

import geopandas

import pandas as pd

import pandas_alive

import contextily

import matplotlib.pyplot as plt

region_gdf = geopandas.read_file(‘data/geo-data/italy-with-regions’)

region_gdf.NOME_REG = region_gdf.NOME_REG.str.lower().str.title()

region_gdf = region_gdf.replace(‘Trentino-Alto Adige/Sudtirol’, ‘Trentino-Alto Adige’)

region_gdf = region_gdf.replace(“Valle D’Aosta/Vallée D’Aoste\r\nValle D’Aosta/Vallée D’Aoste”, “Valle d’Aosta”)

italy_df = pd.read_csv(‘data/Regional Data - Sheet1.csv’, index_col=0, header=1, parse_dates=[0])

italy_df = italy_df[italy_df[‘Region’] != ‘NA’]

cases_df = italy_df.iloc[:, :3]

cases_df[‘Date’] = cases_df.index

pivoted = cases_df.pivot(values=‘New positives’, index=‘Date’, columns=‘Region’)

pivoted.columns = pivoted.columns.astype(str)

pivoted = pivoted.rename(columns={‘nan’: ‘Unknown Region’})

cases_gdf = pivoted.T

cases_gdf[‘geometry’] = cases_gdf.index.map(region_gdf.set_index(‘NOME_REG’)[‘geometry’].to_dict())

cases_gdf = cases_gdf[cases_gdf[‘geometry’].notna()]

cases_gdf = geopandas.GeoDataFrame(cases_gdf, crs=region_gdf.crs, geometry=cases_gdf.geometry)

gdf = cases_gdf

result = gdf.iloc[:, :22]

result[‘geometry’] = gdf.iloc[:, -1:][‘geometry’]

gdf = result

map_chart = gdf.plot_animated(basemap_format={‘source’: contextily.providers.Stamen.Terrain}, cmap=‘viridis’)

cases_df = pivoted

cases_df = cases_df.iloc[:22, :]

from datetime import datetime

bar_chart = cases_df.sum(axis=1).plot_animated(

kind=‘line’,

label_events={

‘Schools Close’: datetime.strptime(“4/03/2020”, “%d/%m/%Y”),

‘Phase I Lockdown’: datetime.strptime(“11/03/2020”, “%d/%m/%Y”),

# ‘1M Global Cases’: datetime.strptime(“02/04/2020”, “%d/%m/%Y”),

# ‘100k Global Deaths’: datetime.strptime(“10/04/2020”, “%d/%m/%Y”),

# ‘Manufacturing Reopens’: datetime.strptime(“26/04/2020”, “%d/%m/%Y”),

# ‘Phase II Lockdown’: datetime.strptime(“4/05/2020”, “%d/%m/%Y”),

},

fill_under_line_color=“blue”,

add_legend=False

)

map_chart.ax.set_title(‘Cases by Location’)

line_chart = (

cases_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’: .1, ‘s’: s, ‘ha’: ‘right’, ‘size’: 11}

race_chart = cases_df.cumsum().plot_animated(

n_visible=5, title=“Cases by Region”, period_label=False, period_summary_func=current_total

)

import time

timestr = time.strftime(“%d/%m/%Y”)

plots = [bar_chart, race_chart, map_chart, line_chart]

# Otherwise titles overlap and adjust_subplot does nothing

from matplotlib import rcParams

from matplotlib.animation import FuncAnimation

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(race_chart.title)

race_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(line_chart.title)

line_chart.ax = f3_ax4

axes = [f3_ax1, f3_ax2, f3_ax3, f3_ax4]

timestr = cases_df.index.max().strftime(“%d/%m/%Y”)

figs.suptitle(f"Italy COVID-19 Confirmed Cases up to {timestr}")

pandas_alive.animate_multiple_plots(

‘examples/italy-covid.gif’,

plots,

figs,

enable_progress_bar=True

)

15 单摆运动

def simple():

import pandas as pd

import matplotlib.pyplot as plt

import pandas_alive

import numpy as np

# Physical constants

g = 9.81

L = .4

mu = 0.2

THETA_0 = np.pi * 70 / 180  # init angle = 70degs

THETA_DOT_0 = 0  # no init angVel

DELTA_T = 0.01  # time stepping

T = 1.5  # time period

# Definition of ODE (ordinary differential equation)

def get_theta_double_dot(theta, theta_dot):

return -mu * theta_dot - (g / L) * np.sin(theta)

# Solution to the differential equation

def pendulum(t):

# initialise changing values

theta = THETA_0

theta_dot = THETA_DOT_0

delta_t = DELTA_T

ang = []

ang_vel = []

ang_acc = []

times = []

for time in np.arange(0, t, delta_t):

theta_double_dot = get_theta_double_dot(

theta, theta_dot

)

theta += theta_dot * delta_t

theta_dot += theta_double_dot * delta_t

times.append(time)

ang.append(theta)

ang_vel.append(theta_dot)

ang_acc.append(theta_double_dot)

data = np.array([ang, ang_vel, ang_acc])

return pd.DataFrame(data=data.T, index=np.array(times), columns=[“angle”, “ang_vel”, “ang_acc”])

# units used for ref: [“angle [rad]”, “ang_vel [rad/s]”, “ang_acc [rad/s^2]”]

df = pendulum(T)

df.index.names = [“Time (s)”]

print(df)

# generate dataFrame for animated bubble plot

df2 = pd.DataFrame(index=df.index)

df2[“dx (m)”] = L * np.sin(df[“angle”])

df2[“dy (m)”] = -L * np.cos(df[“angle”])

df2[“ang_vel”] = abs(df[“ang_vel”])

df2[“size”] = df2[“ang_vel”] * 100  # scale angular vels to get nice size on bubble plot

print(df2)

# static pandas plots

# print(plt.style.available)

# NOTE: 2 lines below required in Jupyter to switch styles correctly

plt.rcParams.update(plt.rcParamsDefault)

plt.style.use(“ggplot”)  # set plot style

fig, (ax1a, ax2b) = plt.subplots(1, 2, figsize=(8, 4), dpi=100)  # 1 row, 2 subplots

# fig.subplots_adjust(wspace=0.1)      # space subplots in row

fig.set_tight_layout(True)

fontsize = “small”

df.plot(ax=ax1a).legend(fontsize=fontsize)

ax1a.set_title(“Outputs vs Time”, fontsize=“medium”)

ax1a.set_xlabel(‘Time [s]’, fontsize=fontsize)

ax1a.set_ylabel(‘Amplitudes’, fontsize=fontsize);

df.plot(ax=ax2b, x=“angle”, y=[“ang_vel”, “ang_acc”]).legend(fontsize=fontsize)

ax2b.set_title(“Outputs vs Angle | Phase-Space”, fontsize=“medium”)

ax2b.set_xlabel(‘Angle [rad]’, fontsize=fontsize)

ax2b.set_ylabel(‘Angular Velocity / Acc’, fontsize=fontsize)

# sample scatter plot with colorbar

fig, ax = plt.subplots()

sc = ax.scatter(df2[“dx (m)”], df2[“dy (m)”], s=df2[“size”] * .1, c=df2[“ang_vel”], cmap=“jet”)

cbar = fig.colorbar(sc)

cbar.set_label(label=“ang_vel [rad/s]”, fontsize=“small”)

# sc.set_clim(350, 400)

ax.tick_params(labelrotation=0, labelsize=“medium”)

ax_scale = 1.

ax.set_xlim(-L * ax_scale, L * ax_scale)

ax.set_ylim(-L * ax_scale - 0.1, L * ax_scale - 0.1)

# make axes square: a circle shows as a circle

ax.set_aspect(1 / ax.get_data_ratio())

ax.arrow(0, 0, df2[“dx (m)”].iloc[-1], df2[“dy (m)”].iloc[-1],

color=“dimgray”, ls=“:”, lw=2.5, width=.0, head_width=0, zorder=-1

)

ax.text(0, 0.15, s=“size and colour of pendulum bob\nbased on pd column\nfor angular velocity”,

ha=‘center’, va=‘center’)

# plt.show()

dpi = 100

ax_scale = 1.1

figsize = (3, 3)

fontsize = “small”

# set up figure to pass onto pandas_alive

# NOTE: by using Figure (capital F) instead of figure() FuncAnimation seems to run twice as fast!

# fig1, ax1 = plt.subplots()

fig1 = plt.Figure()

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)

enter’, va=‘center’)

# plt.show()

dpi = 100

ax_scale = 1.1

figsize = (3, 3)

fontsize = “small”

# set up figure to pass onto pandas_alive

# NOTE: by using Figure (capital F) instead of figure() FuncAnimation seems to run twice as fast!

# fig1, ax1 = plt.subplots()

fig1 = plt.Figure()

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-hMExmGdF-1713246226630)]

[外链图片转存中…(img-O5vcLaZi-1713246226631)]

[外链图片转存中…(img-HbbcpLK6-1713246226631)]

[外链图片转存中…(img-B3XhrSKr-1713246226631)]

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)

img
  • 21
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值