99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線(xiàn)電話(huà):13121318867

登錄
首頁(yè)精彩閱讀厲害了,用Python繪制動(dòng)態(tài)可視化圖表,并保存成gif格式
厲害了,用Python繪制動(dòng)態(tài)可視化圖表,并保存成gif格式
2022-02-22
收藏

厲害了,用Python繪制動(dòng)態(tài)可視化圖表,并保存成gif格式

來(lái)源:俊欣

作者:關(guān)于數(shù)據(jù)分析與可視化

有粉絲問(wèn)道說(shuō)“是不是可以將這些動(dòng)態(tài)的可視化圖表保存成gif圖”,小編立馬就回復(fù)了說(shuō)后面會(huì)寫(xiě)一篇相關(guān)的文章來(lái)介紹如何進(jìn)行保存gif格式的文件。那么我們就開(kāi)始進(jìn)入主題,來(lái)談一下Python當(dāng)中的gif模塊。

安裝相關(guān)的模塊

首先第一步的話(huà)我們需要安裝相關(guān)的模塊,通過(guò)pip命令來(lái)安裝

pip install gif

另外由于gif模塊之后會(huì)被當(dāng)做是裝飾器放在繪制可視化圖表的函數(shù)上,主要我們依賴(lài)的還是Python當(dāng)中繪制可視化圖表的matplotlib、plotly、以及altair這些模塊,因此我們還需要下面這幾個(gè)庫(kù)

pip install "gif[altair]" pip install "gif[matplotlib]" pip install "gif[plotly]" 

gif和matplotlib的結(jié)合

我們先來(lái)看gifmatplotlib模塊的結(jié)合,我們先來(lái)看一個(gè)簡(jiǎn)單的例子,代碼如下

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

厲害了,用Python繪制動(dòng)態(tài)可視化圖表,并保存成gif格式

代碼的邏輯并不難理解,首先我們需要定義一個(gè)函數(shù)來(lái)繪制圖表并且?guī)?/span>gif裝飾器,接著我們需要一個(gè)空的列表,通過(guò)for循環(huán)將繪制出來(lái)的對(duì)象放到這個(gè)空列表當(dāng)中然后保存成gif格式的文件即可。

gif和plotly的結(jié)合

除了和matplotlib的聯(lián)用之外,gifplotly之間也可以結(jié)合起來(lái)用,代碼如下

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

厲害了,用Python繪制動(dòng)態(tài)可視化圖表,并保存成gif格式

整體的代碼邏輯和上面的相似,這里也就不做具體的說(shuō)明了

matplotlib多子圖動(dòng)態(tài)可視化

上面繪制出來(lái)的圖表都是在單張圖表當(dāng)中進(jìn)行的,那當(dāng)然了我們還可以在多張子圖中進(jìn)行動(dòng)態(tài)可視化的展示,代碼如下

# 讀取數(shù)據(jù) 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, "文件名稱(chēng).gif", duration=0.5, unit='s')

output

厲害了,用Python繪制動(dòng)態(tài)可視化圖表,并保存成gif格式

動(dòng)態(tài)氣泡圖

最后我們用plotly模塊來(lái)繪制一個(gè)動(dòng)態(tài)的氣泡圖,代碼如下

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

厲害了,用Python繪制動(dòng)態(tài)可視化圖表,并保存成gif格式

數(shù)據(jù)分析咨詢(xún)請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線(xiàn)
立即咨詢(xún)
客服在線(xiàn)
立即咨詢(xún)
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶(hù)后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見(jiàn):http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }