【Python】高大上!5個(gè)python高級(jí)可視化圖表!
共 7465字,需瀏覽 15分鐘
·
2024-05-25 12:00
以下示例代碼使用Holoviews & Bokeh創(chuàng)建和弦圖,展示5個(gè)不同國(guó)家之間的貿(mào)易關(guān)系。
import holoviews as hvfrom holoviews import optsimport pandas as pdimport numpy as nphv.extension('bokeh')# Sample matrix representing the export volumes between 5 countriesexport_data = np.array([[0, 50, 30, 20, 10],[10, 0, 40, 30, 20],[20, 10, 0, 35, 25],[30, 20, 10, 0, 40],[25, 15, 30, 20, 0]])labels = ['USA', 'China', 'Germany', 'Japan', 'India']# Creating a pandas DataFramedf = pd.DataFrame(export_data, index=labels, columns=labels)df = df.stack().reset_index()df.columns = ['source', 'target', 'value']# Creating a Chord objectchord = hv.Chord(df)# Styling the Chord diagramchord.opts(opts.Chord(cmap='Category20', edge_cmap='Category20',labels='source', label_text_font_size='10pt',edge_color='source', node_color='index',width=700, height=700)).select(value=(5, None))# Display the plotchord
https://holoviews.org/reference/elements/matplotlib/Chord.html
https://github.com/moshi4/pyCirclize
2. 旭日?qǐng)D(Sunburst Chart)
import plotly.express as pximport numpy as npdf = px.data.gapminder().query("year == 2007")fig = px.sunburst(df, path=['continent', 'country'],values='pop',color='lifeExp',hover_data=['iso_alpha'],color_continuous_scale='RdBu',color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))fig.show()
https://plotly.com/python/sunburst-charts/
3. 六邊形箱圖(Hexbin Plot)
六邊形箱圖(通常稱為六邊形分箱圖或六邊形熱力圖)是一種非常有效的可視化工具,用于展示二維數(shù)據(jù)分布,尤其是在數(shù)據(jù)點(diǎn)過于密集而導(dǎo)致傳統(tǒng)散點(diǎn)圖難以區(qū)分單個(gè)點(diǎn)的情況下。這種方法將數(shù)據(jù)空間劃分為一系列六邊形單元(或“箱”),并根據(jù)每個(gè)單元中的數(shù)據(jù)點(diǎn)數(shù)量進(jìn)行著色,從而提供了數(shù)據(jù)分布情況的直觀表示。
import numpy as npimport matplotlib.pyplot as pltfrom mplhexbin import HexBin# 假設(shè)的模擬數(shù)據(jù)np.random.seed(0) # 確保結(jié)果可復(fù)現(xiàn)n_points = 10000x = np.random.rand(n_points) * 100 # 空氣質(zhì)量指數(shù)(AQI)范圍從0到100y = 5 * np.sin(x * np.pi / 50) + np.random.randn(n_points) * 15 # 假設(shè)的醫(yī)院就診數(shù)量,與AQI相關(guān)但具有噪聲# 創(chuàng)建一個(gè)新的圖形fig, ax = plt.subplots(figsize=(10, 8))# 使用HexBin創(chuàng)建六邊形分箱圖hb = HexBin(ax, gridsize=20, cmap='viridis', extent=[0, 100, -30, 50]) # 設(shè)置網(wǎng)格大小、顏色映射和范圍hb.hexbin(x, y, mincnt=1) # 繪制六邊形分箱圖,mincnt設(shè)置最小計(jì)數(shù)閾值# 添加標(biāo)題和軸標(biāo)簽ax.set_title('空氣質(zhì)量指數(shù)(AQI)與醫(yī)院就診數(shù)量的關(guān)系')ax.set_xlabel('空氣質(zhì)量指數(shù)(AQI)')ax.set_ylabel('醫(yī)院就診數(shù)量')# 顯示圖形plt.colorbar(hb.cmap, ax=ax, label='數(shù)據(jù)點(diǎn)數(shù)量') # 添加顏色條并設(shè)置標(biāo)簽plt.show()
https://matplotlib.org/stable/gallery/statistics/hexbin_demo.html
4. 桑基圖(Sankey Diagram)
Plotly庫(kù)可以用來(lái)創(chuàng)建如下所示的桑基圖。以下代碼表示能量從生產(chǎn)源流向小城市的消費(fèi)者。
import plotly.graph_objects as golabels = ["Coal", "Solar", "Wind", "Nuclear", "Residential", "Industrial", "Commercial"]source = [0, 1, 2, 3, 0, 1, 2, 3]target = [4, 4, 4, 4, 5, 5, 5, 5]value = [25, 10, 40, 20, 30, 15, 25, 35]# Create the Sankey diagram objectfig = go.Figure(data=[go.Sankey(node=dict(pad=15,thickness=20,line=dict(color="black", width=0.5),label=labels),link=dict(source=source,target=target,value=value))])fig.update_layout(title_text="Energy Flow in Model City", font_size=12)fig.show()
https://plotly.com/python/sankey-diagram/
5. 主題河流圖(Stream Graph/ Theme River)
Altair數(shù)據(jù)可視化庫(kù)可用于繪制流圖,如下所示。
import altair as altfrom vega_datasets import datasource = data.unemployment_across_industries.urlalt.Chart(source).mark_area().encode(alt.X('yearmonth(date):T',axis=alt.Axis(format='%Y', domain=False, tickSize=0)),alt.Y('sum(count):Q', stack='center', axis=None),alt.Color('series:N',scale=alt.Scale(scheme='category20b'))).interactive()
https://altair-viz.github.io/gallery/streamgraph.html
往期精彩回顧
交流群
歡迎加入機(jī)器學(xué)習(xí)愛好者微信群一起和同行交流,目前有機(jī)器學(xué)習(xí)交流群、博士群、博士申報(bào)交流、CV、NLP等微信群,請(qǐng)掃描下面的微信號(hào)加群,備注:”昵稱-學(xué)校/公司-研究方向“,例如:”張小明-浙大-CV“。請(qǐng)按照格式備注,否則不予通過。添加成功后會(huì)根據(jù)研究方向邀請(qǐng)進(jìn)入相關(guān)微信群。請(qǐng)勿在群內(nèi)發(fā)送廣告,否則會(huì)請(qǐng)出群,謝謝理解~(也可以加入機(jī)器學(xué)習(xí)交流qq群772479961)
