社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Top 5 Python 数据可视化技术

小白玩转Python • 3 周前 • 39 次点击  

点击下方卡片,关注“小白玩转Python”公众号


掌握这五种高级可视化图表将使数据可视化变得容易。这些库互为补充,以最大化数据表达。

和弦图 (Chord Diagram)
和弦图创造性地展示了数据点之间复杂的关系。节点围绕一个圆圈排列,通过弧线连接。弧线的长度反映了连接值,其粗细表示关系的重要性。颜色对数据进行分类,使比较变得容易。广泛应用于各个领域,特别是在可视化遗传数据方面。
以下是一个使用 Holoviews & Bokeh 创建显示五个国家之间贸易关系的和弦图的示例。
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

Sunburst Chart
Sunburst Chart 通过清晰展示层次数据,超越了传统的饼图和环图。它使用同心圆,每个圆代表层次中的一级。中心是根,扇形表示节点。每个扇形的大小反映了它的值,直观地理解数据的重要性。在可视化文件系统层次结构、用户导航路径、市场细分和遗传数据方面非常有用。以下是一个使用 Plotly 库创建Sunburst Chart 的示例。
import plotly.express as pximport numpy as np
df = 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/

六边形分箱图 (Hexbin Plot)
六边形分箱图,或称六边形分箱,对于可视化二维数据分布非常有效,特别是当数据点密集时。它将数据空间划分为六边形箱,颜色表示每个箱中的点数,清晰地表示数据分布。
以下是一个使用 Python 和 Matplotlib 创建六边形分箱图的示例,展示了空气质量指数 (AQI) 与医院访问之间的相关性。
import numpy as npimport matplotlib.pyplot as pltfrom mplhexbin import HexBin
# Simulated datanp.random.seed(0) # Ensure reproducibilityn_points = 10000x = np.random.rand(n_points) * 100 # Air Quality Index (AQI) range from 0 to 100y = 5 * np.sin(x * np.pi / 50) + np.random.randn(n_points) * 15 # Simulated hospital visits, related to AQI but with noise
# Create a new figurefig, ax = plt.subplots(figsize=(10, 8))
# Use HexBin to create a hexagonal bin plothb = HexBin(ax, gridsize=20, cmap='viridis', extent=[0, 100, -30, 50]) # Set grid size, colormap, and rangehb.hexbin(x, y, mincnt=1) # Draw the hexagonal bin plot, mincnt sets the minimum count threshold
# Add title and axis labelsax.set_title('Relationship between Air Quality Index (AQI) and Hospital Visits')ax.set_xlabel('Air Quality Index (AQI)')ax.set_ylabel('Hospital Visits')
# Show the figureplt.colorbar(hb.cmap, ax=ax, label='Number of Data Points') # Add color bar and set labelplt.show()

参考链接:
https://matplotlib.org/stable/gallery/statistics/hexbin_demo.html

桑基图 (Sankey Diagram)
桑基图可视化数据流,非常适合能源、材料和财务数据。以 Matthew Henry Phineas Riall Sankey 命名,它显示了系统各阶段或部分之间的流量。节点宽度与流量数量成比例,易于理解数据规模和方向。
以下是一个使用 Python 创建桑基图的示例,展示了从生产源头到小城市消费者的能量流。
import plotly.graph_objects as go
labels = ["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/

流图 (Stream Graph, 主题河流)
流图类似于河流,描绘了随时间的变化。颜色区分类别,而“河流”的宽度表示每个类别的值。它直观地展示趋势和关系,易于理解数据动态。
以下是一个使用 Altair 库创建流图的示例。
import altair as altfrom vega_datasets import data
source = data.unemployment_across_industries.url
alt.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

·  END  ·

🌟 想要变身计算机视觉小能手?快来「小白玩转Python」公众号!
回复Python视觉实战项目,解锁31个超有趣的视觉项目大礼包!🎁

本文仅供学习交流使用,如有侵权请联系作者删除

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/179006
 
39 次点击