教你如何用 Python 三行代码做动图!
作者 | 小F 责编 | 张文
头图 | CSDN 下载自东方 IC
来源 | 法纳斯特(ID:walker398)
关于动态条形图,小F以前推荐过 Bar、 Chart、 Race 这个库。三行代码就能实现动态条形图的绘制。但有些同学在使用的时候,会出现一些错误。一个是加载文件报错,另一个是生成 GIF 的时候报错。这是因为作者的示例是网络加载数据,会读取不到。通过读取本地文件,就不会出错。GIF 生成失败一般是需要安装 imagemagick (图片处理工具)。
最近小 F 又发现一个可视化图库 Pandas_Alive,不仅包含动态条形图,还可以绘制动态曲线图、气泡图、饼状图、地图等。
同样也是几行代码就能完成动态图表的绘制。
GitHub地址:https://github.com/JackMcKew/pandas_alive
使用文档:https://jackmckew.github.io/pandas_alive/
安装版本建议是0.2.3,matplotlib版本是3.2.1。
同时需自行安装 tqdm (显示进度条)和 descartes (绘制地图相关库)。
要不然会出现报错,估计是作者的 requestment.txt 没包含这两个库。
好了,成功安装后就可以引入这个第三方库,直接选择加载本地文件。
import pandas_alive
import pandas as pdcovid_df = pd.read_csv('data/covid19.csv', index_col=0, parse_dates=[0])
covid_df.plot_animated(filename='examples/example-barh-chart.gif', n_visible=15)
生成了一个 GIF 图,具体如下:
刚开始学习这个库的时候,大家可以减少数据,这样生成 GIF 的时间就会快一些。
比如小 F 在接下来的实践中,基本都只选取了 20 天左右的数据。
对于其他图表,我们可以查看官方文档的 API 说明,得以了解。
下面我们就来看看其他动态图表的绘制方法吧!
动态条形图
elec_df = pd.read_csv("data/Aus_Elec_Gen_1980_2018.csv", index_col=0, parse_dates=[0], thousands=',')
elec_df = elec_df.iloc[:20, :]
elec_df.fillna(0).plot_animated('examples/example-electricity-generated-australia.gif', period_fmt="%Y",title='Australian Electricity Generation Sources 1980-2018')
动态柱状图
covid_df = pd.read_csv('data/covid19.csv', index_col=0, parse_dates=[0])
covid_df.plot_animated(filename='examples/example-barv-chart.gif', orientation='v', n_visible=15)
动态曲线图
covid_df = pd.read_csv('data/covid19.csv', index_col=0, parse_dates=[0])
covid_df.diff().fillna(0).plot_animated(filename='examples/example-line-chart.gif', kind='line', period_label={'x': 0.25, 'y': 0.9})
动态面积图
covid_df = pd.read_csv('data/covid19.csv', index_col=0, parse_dates=[0])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)
动态散点图
max_temp_df = pd.read_csv("data/Newcastle_Australia_Max_Temps.csv",parse_dates={"Timestamp": ["Year", "Month", "Day"]},
)
min_temp_df = pd.read_csv("data/Newcastle_Australia_Min_Temps.csv",parse_dates={"Timestamp": ["Year", "Month", "Day"]},
)max_temp_df = max_temp_df.iloc[:5000, :]
min_temp_df = min_temp_df.iloc[:5000, :]merged_temp_df = pd.merge_asof(max_temp_df, min_temp_df, on="Timestamp")
merged_temp_df.index = pd.to_datetime(merged_temp_df["Timestamp"].dt.strftime('%Y/%m/%d'))keep_columns = ["Minimum temperature (Degree C)", "Maximum temperature (Degree C)"]
merged_temp_df[keep_columns].resample("Y").mean().plot_animated(filename='examples/example-scatter-chart.gif', kind="scatter",title='Max & Min Temperature Newcastle, Australia')
动态饼状图
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})
动态气泡图
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)
地理空间点图表
import geopandas
import pandas_alive
import contextilygdf = 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})
多边形地理图表
import geopandas
import pandas_alive
import contextilygdf = 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})
多个动态图表
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)
城市人口
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)
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].valuesdata = 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 )
新南威尔斯州COVID可视化
def nsw():import geopandasimport pandas as pdimport pandas_aliveimport contextilyimport matplotlib.pyplot as pltimport jsonwith open('data/package_show.json', 'r', encoding='utf8')as fp:data = json.load(fp)# Extract url to csv componentcovid_nsw_data_url = data["result"]["resources"][0]["url"]print(covid_nsw_data_url)# Read csv from data API urlnsw_covid = pd.read_csv('data/confirmed_cases_table1_location.csv')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.index# gdf.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 Mercatorresult = gdf.iloc[:, :22]result['geometry'] = gdf.iloc[:, -1:]['geometry']gdf = resultmap_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 datetimebar_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 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)
意大利COVID可视化
def italy(): import geopandas import pandas as pd import pandas_alive import contextily import matplotlib.pyplot as pltregion_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_gdfresult = gdf.iloc[:, :22] result['geometry'] = gdf.iloc[:, -1:]['geometry'] gdf = resultmap_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 datetimebar_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 timetimestr = 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 FuncAnimationrcParams.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_ax1f3_ax2 = figs.add_subplot(gs[1, 0]) f3_ax2.set_title(race_chart.title) race_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(line_chart.title) line_chart.ax = f3_ax4axes = [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 )
单摆运动
def simple():import pandas as pdimport matplotlib.pyplot as pltimport pandas_aliveimport numpy as np# Physical constantsg = 9.81L = .4mu = 0.2THETA_0 = np.pi * 70 / 180 # init angle = 70degsTHETA_DOT_0 = 0 # no init angVelDELTA_T = 0.01 # time steppingT = 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 equationdef pendulum(t):# initialise changing valuestheta = THETA_0theta_dot = THETA_DOT_0delta_t = DELTA_Tang = []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_ttheta_dot += theta_double_dot * delta_ttimes.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 plotdf2 = 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 plotprint(df2)# static pandas plots## print(plt.style.available)# NOTE: 2 lines below required in Jupyter to switch styles correctlyplt.rcParams.update(plt.rcParamsDefault)plt.style.use("ggplot") # set plot stylefig, (ax1a, ax2b) = plt.subplots(1, 2, figsize=(8, 4), dpi=100) # 1 row, 2 subplots# fig.subplots_adjust(wspace=0.1) # space subplots in rowfig.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 colorbarfig, 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 circleax.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 = 100ax_scale = 1.1figsize = (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()ax1 = fig1.add_subplot()fig1.set_size_inches(figsize)ax1.set_title("Simple pendulum animation, L=" + str(L) + "m", fontsize="medium")ax1.set_xlabel("Time (s)", color='dimgray', fontsize=fontsize)ax1.set_ylabel("Amplitudes", color='dimgray', fontsize=fontsize)ax1.tick_params(labelsize=fontsize)# pandas_aliveline_chart = df.plot_animated(filename="pend-line.gif", kind='line', period_label={'x': 0.05, 'y': 0.9},steps_per_period=1, interpolate_period=False, period_length=50,period_fmt='Time:{x:10.2f}',enable_progress_bar=True, fixed_max=True, dpi=100, fig=fig1)plt.close()# Video('examples/pend-line.mp4', html_attributes="controls muted autoplay")# set up and generate animated scatter plot## set up figure to pass onto `pandas_alive`# NOTE: by using Figure (capital F) instead of figure() `FuncAnimation` seems to run twice as fast!fig1sc = plt.Figure()ax1sc = fig1sc.add_subplot()fig1sc.set_size_inches(figsize)ax1sc.set_title("Simple pendulum animation, L=" + str(L) + "m", fontsize="medium")ax1sc.set_xlabel("Time (s)", color='dimgray', fontsize=fontsize)ax1sc.set_ylabel("Amplitudes", color='dimgray', fontsize=fontsize)ax1sc.tick_params(labelsize=fontsize)# pandas_alivescatter_chart = df.plot_animated(filename="pend-scatter.gif", kind='scatter', period_label={'x': 0.05, 'y': 0.9},steps_per_period=1, interpolate_period=False, period_length=50,period_fmt='Time:{x:10.2f}',enable_progress_bar=True, fixed_max=True, dpi=100, fig=fig1sc, size="ang_vel")plt.close()print("Points size follows one of the pd columns: ang_vel")# Video('./pend-scatter.gif', html_attributes="controls muted autoplay")# set up and generate animated bar race chart## set up figure to pass onto `pandas_alive`# NOTE: by using Figure (capital F) instead of figure() `FuncAnimation` seems to run twice as fast!fig2 = plt.Figure()ax2 = fig2.add_subplot()fig2.set_size_inches(figsize)ax2.set_title("Simple pendulum animation, L=" + str(L) + "m", fontsize="medium")ax2.set_xlabel("Amplitudes", color='dimgray', fontsize=fontsize)ax2.set_ylabel("", color='dimgray', fontsize="x-small")ax2.tick_params(labelsize=fontsize)# pandas_aliverace_chart = df.plot_animated(filename="pend-race.gif", kind='race', period_label={'x': 0.05, 'y': 0.9},steps_per_period=1, interpolate_period=False, period_length=50,period_fmt='Time:{x:10.2f}',enable_progress_bar=True, fixed_max=False, dpi=100, fig=fig2)plt.close()# set up and generate bubble animated plot## set up figure to pass onto `pandas_alive`# NOTE: by using Figure (capital F) instead of figure() `FuncAnimation` seems to run twice as fast!fig3 = plt.Figure()ax3 = fig3.add_subplot()fig3.set_size_inches(figsize)ax3.set_title("Simple pendulum animation, L=" + str(L) + "m", fontsize="medium")ax3.set_xlabel("Hor Displacement (m)", color='dimgray', fontsize=fontsize)ax3.set_ylabel("Ver Displacement (m)", color='dimgray', fontsize=fontsize)# limits & ratio below get the graph squareax3.set_xlim(-L * ax_scale, L * ax_scale)ax3.set_ylim(-L * ax_scale - 0.1, L * ax_scale - 0.1)ratio = 1. # this is visual ratio of axesax3.set_aspect(ratio / ax3.get_data_ratio())ax3.arrow(0, 0, df2["dx (m)"].iloc[-1], df2["dy (m)"].iloc[-1],color="dimgray", ls=":", lw=1, width=.0, head_width=0, zorder=-1)# pandas_alivebubble_chart = df2.plot_animated(kind="bubble", filename="pend-bubble.gif",x_data_label="dx (m)", y_data_label="dy (m)",size_data_label="size", color_data_label="ang_vel", cmap="jet",period_label={'x': 0.05, 'y': 0.9}, vmin=None, vmax=None,steps_per_period=1, interpolate_period=False, period_length=50, period_fmt='Time:{x:10.2f}s',enable_progress_bar=True, fixed_max=False, dpi=dpi, fig=fig3)plt.close()print("Bubble size & colour animates with pd data column for ang_vel.")# Combined plots#fontsize = "x-small"# Otherwise titles overlap and subplots_adjust does nothingfrom matplotlib import rcParamsrcParams.update({"figure.autolayout": False})figs = plt.Figure(figsize=(9, 4), dpi=100)figs.subplots_adjust(wspace=0.1)gs = figs.add_gridspec(2, 2)ax1 = figs.add_subplot(gs[0, 0])ax1.set_xlabel("Time(s)", color='dimgray', fontsize=fontsize)ax1.set_ylabel("Amplitudes", color='dimgray', fontsize=fontsize)ax1.tick_params(labelsize=fontsize)ax2 = figs.add_subplot(gs[1, 0])ax2.set_xlabel("Amplitudes", color='dimgray', fontsize=fontsize)ax2.set_ylabel("", color='dimgray', fontsize=fontsize)ax2.tick_params(labelsize=fontsize)ax3 = figs.add_subplot(gs[:, 1])ax3.set_xlabel("Hor Displacement (m)", color='dimgray', fontsize=fontsize)ax3.set_ylabel("Ver Displacement (m)", color='dimgray', fontsize=fontsize)ax3.tick_params(labelsize=fontsize)# limits & ratio below get the graph squareax3.set_xlim(-L * ax_scale, L * ax_scale)ax3.set_ylim(-L * ax_scale - 0.1, L * ax_scale - 0.1)ratio = 1. # this is visual ratio of axesax3.set_aspect(ratio / ax3.get_data_ratio())line_chart.ax = ax1race_chart.ax = ax2bubble_chart.ax = ax3plots = [line_chart, race_chart, bubble_chart]# pandas_alive combined using custom figurepandas_alive.animate_multiple_plots(filename='pend-combined.gif', plots=plots, custom_fig=figs, dpi=100, enable_progress_bar=True,adjust_subplot_left=0.2, adjust_subplot_right=None,title="Simple pendulum animations, L=" + str(L) + "m", title_fontsize="medium")plt.close()
最后如果你想完成中文动态图表的制作,加入中文显示代码即可。
# 中文显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows
plt.rcParams['font.sans-serif'] = ['Hiragino Sans GB'] # Mac
plt.rcParams['axes.unicode_minus'] = False# 读取数据
df_result = pd.read_csv('data/yuhuanshui.csv', index_col=0, parse_dates=[0])
# 生成图表
animated_line_chart = df_result.diff().fillna(0).plot_animated(kind='line', period_label=False, add_legend=False)
animated_bar_chart = df_result.plot_animated(n_visible=10)
pandas_alive.animate_multiple_plots('examples/yuhuanshui.gif',[animated_bar_chart, animated_line_chart], enable_progress_bar=True,title='我是余欢水演职人员热度排行')
还是使用演员的百度指数数据。
更多精彩推荐☞GitHub 年度报告正式发布,JavaScript 霸榜、TypeScript 爆发!☞中国实现量子计算第一个里程碑:原型机 “九章”比最快的超级计算机快一百万亿倍☞虚拟偶像出道,技术「造星」推动下的粉丝经济 ☞酷派奖励程序员10 万股期权!因代码贡献受 Linux 之父亲自点名赞赏☞前端的魔爪已经伸到后端了,颤抖吧后端!☞常年“盘踞”数据库前五的 MongoDB,在中国有哪些新动向?☞开发者实测 M1 芯片报告:除了大型应用程序启动慢点,整体性能优秀
点分享点点赞点在看
教你如何用 Python 三行代码做动图!相关推荐
- 用【python】自做动图
代码如下: from PIL import Image, ImageSequence, ImageFont import matplotlib.pyplot as plt import os, ran ...
- python批量删缩进_鬼畜小姐姐+野狼disco,十分钟教你如何用Python剪辑一个牛逼的抖音小视频?...
鬼畜小姐姐+野狼disco,十分钟教你如何用Python剪辑一个牛逼的抖音小视频? 前言 半个月前,后台有个小伙伴问我,如何将视频中的音频提取出来,并且将声音转成文字写入到 word 中,正好接下来的 ...
- 怎么用python制作简单的程序-神级程序员教你如何用python制作一个牛逼的外挂!...
玩过电脑游戏的同学对于外挂肯定不陌生,但是你在用外挂的时候有没有想过如何做一个外挂呢?(当然用外挂不是那么道义哈,呵呵),那我们就来看一下如何用python来制作一个外挂.... 我打开了4399小游 ...
- 教你如何用 Python 来实现一个大数据搜索引擎
搜索是大数据领域里常见的需求.Splunk和ELK分别是该领域在非开源和开源领域里的领导者.本文利用很少的Python代码实现了一个基本的数据搜索功能,试图让大家理解大数据搜索的基本原理. 布隆过滤器 ...
- python excel 打印文档_教你如何用Python轻轻松松操作Excel、Word、CSV,一文就够了,赶紧码住!!!...
原标题:教你如何用Python轻轻松松操作Excel.Word.CSV,一文就够了,赶紧码住!!! 作者:奈何缘浅wyj Python 操作 Excel 常用工具 数据处理是 Python 的一大应用 ...
- 用visio画用例图小人_教你如何用 Python 打飞机 ?
前言:python 除了生孩子 ,啥都会 .包括打飞机 !今天就来教你如何用 python 打飞机 ! 简述 相信你是一个单纯的孩子说的打飞机是指啥意思 ,对吧 ?嗯 ,没毛病 .就是 pygame ...
- python表白-教你如何用Python表白
哈哈哈哈,程序猿怎么可能有女朋友. 额,开玩笑的,程序猿不仅有女朋友,而且温柔贤惠,聪明大方. 那么在如此特殊的节日,我们就要用我们的技术去赢得女神的芳心. 今天介绍如何用Python一行代码表白. ...
- python编程怎么建立工程_教你如何用Python脚本快速创建项目
相信初学Cocos2D者对Python还很陌生,今天本篇教程教你如何用Python脚本快速创建项目. 在Cocos2d-x2.1.4以上的版本中,取消了使用vs模版创建项目的方法,开始使用python ...
- 手把手教你如何用Python制作一个电子相册?末附python教程
这里简单介绍一下python制作电子相册的过程,主要用到tkinter和pillow这2个库,tkinter用于窗口显示照片,pillow用来处理照片,照片切换分为2种方式,一种是自动切换(每隔5秒) ...
最新文章
- Yii获取当前url和域名
- 目录config.php怎么修改域名,config.php · wlphp/基于宝塔面板api给站点新增删除域名接口 - Gitee.com...
- python编辑器_资深程序员:学Python我推荐你用这几款编辑器
- vuejs对象更新渲染_vue 数组和对象渲染问题
- python 玩公众号游戏_从零基础开始,用python手把手教你玩跳一跳小游戏,直接打出高分...
- oracle 创建视图、修改视图、删除视图、利用视图操作基本表
- c++ 数据类型转换: static_cast、dynamic_cast、reinterpret_cast和const_cast
- 竞价广告系统-广告网络
- SOTIF很快将会取代ISO 26262?为您详细解读SOTIF标准ISO/PAS 21448
- 在Windows中查看文件的MD5值
- 【质量管理】SMT电子厂超实用的六西格玛(6σ)质量管理工具一览表!
- 基于GoogleMap,Mapabc,51ditu,VirtualEarth,YahooMap Api接口的Jquery插件的通用实现(含源代码下载) --转...
- MATLAB编程之PTB: 实验暂停
- 2019前端面试常问
- JavaScript初学入门(JS打印9*9乘法表,JS制作简易计算器)
- 优质百度网盘资源分享(计算机篇)
- 计算机ms高级应用科目一 科目二考什么,什么是科目一、科目二、科目三、科目四?全部都在这!...
- ValueError: cannot resize this array: it does not own its data
- 软件分发linux,软件分发工具 | 自动化软件分发 - ManageEngine Desktop Central
- 离线百度地图,QT添加按钮点击切换卫星地图和街道地图
热门文章
- 【GTK3.0】背景设置
- 尝试笔记 01 之 CSS 边角上的标签
- Codeforces205E Little Elephant and Furik and RubikLittle Elephant and Furik and Rubik
- UIWebView 真机iOS 8.x系统上报错
- 总结ubuntu 在命令界面login incorrect的问题
- [源码]天骄天下个人网站系统(三个月倾情打造)
- C#编码规范2[转]
- 《TensorFlow 2.0深度学习算法实战教材》学习笔记(八、过拟合)
- 地理空间数据Geometry在MySQL中使用(一)
- [LibTorch] C++ 调用 PyTorch 导出的模型