如何利用 Python 绘制动态可视化图表
作者:Python数据挖掘 时间:2022-11-23 17:14:37
一、安装相关的模块
首先第一步的话我们需要安装相关的模块,通过pip
命令来安装
pip install gif
另外由于gif模块之后会被当做是装饰器放在绘制可视化图表的函数上,主要我们依赖的还是Python当中绘制可视化图表的matplotlib
、plotly
、以及altair
这些模块,因此我们还需要下面这几个库
pip install "gif[altair]"
pip install "gif[matplotlib]"
pip install "gif[plotly]"
二、gif和matplotlib的结合
我们先来看gif
和matplotlib
模块的结合,我们先来看一个简单的例子,
代码如下:
import random
from matplotlib import pyplot as plt
import gif
x = [random.randint(0, 100) for _ in range(100)]
y = [random.randint(0, 100) for _ in range(100)]
gif.options.matplotlib["dpi"] = 300
@gif.frame
def plot(i):
xi = x[i*10:(i+1)*10]
yi = y[i*10:(i+1)*10]
plt.scatter(xi, yi)
plt.xlim((0, 100))
plt.ylim((0, 100))
frames = []
for i in range(10):
frame = plot(i)
frames.append(frame)
gif.save(frames, 'example.gif', duration=3.5, unit="s", between="startend")
output:
代码的逻辑并不难理解,首先我们需要定义一个函数来绘制图表并且带上gif
装饰器,接着我们需要一个空的列表,通过for循环将绘制出来的对象放到这个空列表当中然后保存成gif格式的文件即可。
三、gif和plotly的结合
除了和matplotlib
的联用之外,gif
和plotly
之间也可以结合起来用
代码如下:
import random
import plotly.graph_objects as go
import pandas as pd
import gif
df = pd.DataFrame({
't': list(range(10)) * 10,
'x': [random.randint(0, 100) for _ in range(100)],
'y': [random.randint(0, 100) for _ in range(100)]
})
@gif.frame
def plot(i):
d = df[df['t'] == i]
fig = go.Figure()
fig.add_trace(go.Scatter(
x=d["x"],
y=d["y"],
mode="markers"
))
fig.update_layout(width=500, height=300)
return fig
frames = []
for i in range(10):
frame = plot(i)
frames.append(frame)
gif.save(frames, 'example_plotly.gif', duration=100)
output:
整体的代码逻辑和上面的相似,这里也就不做具体的说明了
四、matplotlib多子图动态可视化
上面绘制出来的图表都是在单张图表当中进行的,那当然了我们还可以在多张子图中进行动态可视化的展示,
代码如下:
# 读取数据
df = pd.read_csv('weather_hourly_darksky.csv')
df = df.rename(columns={"time": "date"})
@gif.frame
def plot(df, date):
df = df.loc[df.index[0]:pd.Timestamp(date)]
fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(10, 6), dpi=100)
ax1.plot(df.temperature, marker='o', linestyle='--', linewidth=1, markersize=3, color='g')
maxi = round(df.temperature.max() + 3)
ax1.set_xlim([START, END])
ax1.set_ylim([0, maxi])
ax1.set_ylabel('TEMPERATURE', color='green')
ax2.plot(df.windSpeed, marker='o', linestyle='--', linewidth=1, markersize=3, color='b')
maxi = round(df.windSpeed.max() + 3)
ax2.set_xlim([START, END])
ax2.set_ylim([0, maxi])
ax2.set_ylabel('WIND', color='blue')
ax3.plot(df.visibility, marker='o', linestyle='--', linewidth=1, markersize=3, color='r')
maxi = round(df.visibility.max() + 3)
ax3.set_xlim([START, END])
ax3.set_ylim([0, maxi])
ax3.set_ylabel('VISIBILITY', color='red')
frames = []
for date in pd.date_range(start=df.index[0], end=df.index[-1], freq='1M'):
frame = plot(df, date)
frames.append(frame)
gif.save(frames, "文件名称.gif", duration=0.5, unit='s')
output:
五、动态气泡图
最后我们用plotly
模块来绘制一个动态的气泡图,
代码如下:
import gif
import plotly.graph_objects as go
import numpy as np
np.random.seed(1)
N = 100
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
sz = np.random.rand(N) * 30
layout = go.Layout(
xaxis={'range': [-2, 2]},
yaxis={'range': [-2, 2]},
margin=dict(l=10, r=10, t=10, b=10)
)
@gif.frame
def plot(i):
fig = go.Figure(layout=layout)
fig.add_trace(go.Scatter(
x=x[:i],
y=y[:i],
mode="markers",
marker=go.scatter.Marker(
size=sz[:i],
color=colors[:i],
opacity=0.6,
colorscale="Viridis"
)
))
fig.update_layout(width=500, height=300)
return fig
frames = []
for i in range(100):
frame = plot(i)
frames.append(frame)
gif.save(frames, "bubble.gif")
output:
来源:https://blog.csdn.net/qq_34160248/article/details/123052069
标签:Python,绘制,动态,可视化,图表
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈django开发者模式中的autoreload是如何实现的
2022-04-03 17:22:04
Python+Opencv实现计算闭合区域面积
2023-03-17 03:02:44
![](https://img.aspxhome.com/file/2023/1/92491_0s.png)
怎样处理 MySQL中与文件许可有关的问题
2008-11-27 16:12:00
利用python实现万年历的查询
2023-02-24 03:16:01
![](https://img.aspxhome.com/file/2023/1/92231_0s.jpg)
python面向对象之类属性和类方法案例分析
2022-01-18 06:00:36
![](https://img.aspxhome.com/file/2023/1/118761_0s.png)
python通过wxPython打开一个音频文件并播放的方法
2021-10-20 16:15:08
Python基于随机采样一至性实现拟合椭圆
2022-11-25 01:44:35
![](https://img.aspxhome.com/file/2023/1/101641_0s.png)
Python制作一个随机抽奖小工具的实现
2022-10-22 03:53:29
![](https://img.aspxhome.com/file/2023/3/104973_0s.png)
vue-cli 环境变量 process.env的使用及说明
2024-05-29 22:28:45
![](https://img.aspxhome.com/file/2023/9/123099_0s.png)
javascript设计模式之模块模式学习笔记
2024-04-29 13:16:11
![](https://img.aspxhome.com/file/2023/0/132760_0s.jpg)
python实现画桃心表白
2021-05-14 16:27:00
![](https://img.aspxhome.com/file/2023/8/104998_0s.png)
python3 requests中文乱码之压缩格式问题解析
2021-12-13 17:03:28
SpringBoot集成Flyway进行数据库版本迁移管理的步骤
2024-01-13 19:18:53
![](https://img.aspxhome.com/file/2023/0/83030_0s.png)
python进度条库tqdm的基本操作方法
2021-03-02 08:31:22
关于Python3 lambda函数的深入浅出
2023-01-12 09:12:41
GO语言标准错误处理机制error用法实例
2024-02-13 18:07:20
python计算最小优先级队列代码分享
2022-12-05 03:26:50
Sql Server 开窗函数Over()的使用实例详解
2024-01-17 14:34:33
Python如何通过手肘法实现k_means聚类详解
2021-03-13 16:35:34
![](https://img.aspxhome.com/file/2023/4/127724_0s.png)
轻松掌握SQL Server数据库的六个实用技巧
2009-01-15 12:56:00