欢迎光临
我们一直在努力

Python 数据可视化:从单变量到多变量

Python凭借其强大的可视化库(如Matplotlib、Seaborn)成为进行EDA的首选工具。本文基于一份实用的“Python数据可视化速查表”,系统介绍从单变量到多变量、从时间序列到文本数据的可视化方法,并提供代码示例与扩展解读,助你高效完成数据探索。


1. 单变量分析:了解单个变量分布

单变量分析旨在理解数据集中单个变量的分布特征,适用于数值型和分类型数据。

常用图表与代码示例

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 示例数据框
df = pd.DataFrame({'col': [1, 2, 2, 3, 3, 3, 4, 4, 5]})

# 1. 直方图:查看数值分布
df.hist()
plt.title("数值分布直方图")
plt.show()

# 2. 箱线图:查看分布与离群点(原文borglot应为boxplot)
sns.boxplot(data=df, y='col') # 展示数值列col的分布
plt.title("箱线图展示分布与异常值")
plt.show()

# 3. 核密度估计图:平滑的概率密度曲线
sns.kdeplot(data=df['col'])
plt.title("核密度估计图")
plt.show()

# 4. 条形图:适用于分类数据频次统计
df['col'].value_counts().plot(kind='bar')
plt.title("分类频次条形图")
plt.xlabel("类别")
plt.ylabel("频次")
plt.show()

适用场景:

  • 直方图:了解数值分布是否正态、偏斜
  • 箱线图:快速发现异常值
  • 核密度图:平滑展示分布趋势
  • 条形图:展示类别频次

2. 双变量分析:探索两个变量间关系

双变量分析用于探索两个变量之间的关联,包括数值-数值、数值-类别等组合。

# 示例数据
df = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [2, 4, 6, 8, 10],
'category': ['A', 'B', 'A', 'B', 'A']
})

# 1. 散点图:两个数值变量关系
sns.scatterplot(data=df, x='x', y='y')
plt.title("散点图:x与y的关系")
plt.show()

# 2. 带回归线的散点图
sns.regplot(data=df, x='x', y='y')
plt.title("带线性回归的散点图")
plt.show()

# 3. 条形图:类别与数值的对比
sns.barplot(x='category', y='y', data=df)
plt.title("不同类别的y值对比")
plt.show()

# 4. 小提琴图:类别下的分布与密度
sns.violinplot(data=df, x='category', y='y')
plt.title("小提琴图:类别y的分布")
plt.show()

# 5. 箱线图(原文borglet应为boxplot):比较类别间分布
sns.boxplot(x='category', y='y', data=df)
plt.title("箱线图:类别间分布比较")
plt.show()


3. 多变量分析:三维及以上关系探索

当我们需要同时考察三个或更多变量时,多变量可视化工具显得尤为重要。

# 示例数据
df = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [2, 4, 6, 8, 10],
'z': [5, 4, 3, 2, 1],
'type': ['T1', 'T2', 'T1', 'T2', 'T1']
})

# 1. 散点图矩阵:所有数值变量两两关系
sns.pairplot(df)
plt.suptitle("散点图矩阵", y=1.02)
plt.show()

# 2. 相关热图:变量间相关性强度
sns.heatmap(df.corr(), annot=True, cmap='coolwarm')
plt.title("变量相关性热图")
plt.show()

# 3. 联合分布图:散点图+边缘分布
sns.jointplot(data=df, x='x', y='y')
plt.show()

# 4. 三变量散点图(颜色表示第三维)
plt.scatter(df['x'], df['y'], c=df['z'], cmap='viridis')
plt.colorbar(label='z值')
plt.title("三变量散点图(颜色表示z)")
plt.show()

# 5. 分类着色散点图
sns.scatterplot(data=df, x='x', y='y', hue='type')
plt.title("按类别着色的散点图")
plt.show()


4. 时间序列分析:趋势、周期与异常

时间序列数据常见于金融、气象、日志等领域,可视化有助于识别趋势、季节性和异常。

# 示例时间序列数据
df = pd.DataFrame({
'date': pd.date_range('2023-01-01', periods=100, freq='D'),
'value': np.random.randn(100).cumsum() + 50
})

# 1. 简单时间序列图
df.plot(x='date', y='value')
plt.title("时间序列趋势图")
plt.xlabel("日期")
plt.ylabel("数值")
plt.show()

# 2. 移动平均图(窗口为7天)
df.set_index('date')['value'].rolling(window=7).mean().plot()
plt.title("7天移动平均图")
plt.show()

# 3. 时间序列分解(需statsmodels库)
from statsmodels.tsa.seasonal import seasonal_decompose
result = seasonal_decompose(df.set_index('date')['value'], model='additive', period=30)
result.plot()
plt.suptitle("时间序列分解(趋势+季节+残差)", y=1.02)
plt.show()

# 4. 带置信区间的折线图
sns.lineplot(data=df, x='date', y='value')
plt.title("带置信区间的时间序列图")
plt.show()


5. 文本数据分析:词频、主题与情感

文本数据可视化常用于自然语言处理(NLP),帮助理解词频分布、主题结构等。

from wordcloud import WordCloud
import nltk
from nltk.probability import FreqDist

# 示例文本
text = "data science machine learning python visualization analysis exploration"

# 1. 词云图
wordcloud = WordCloud(width=800, height=400).generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title("词云图")
plt.show()

# 2. 词频分布图
words = text.split()
fdist = FreqDist(words)
fdist.plot(30, cumulative=False) # 显示前30个词
plt.title("词频分布图")
plt.show()

# 3. 词频条形图
sns.barplot(x=list(fdist.keys())[:10], y=list(fdist.values())[:10])
plt.title("前10高频词条形图")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()


6. 图表自定义:美化与标注

好的可视化不仅需要正确表达信息,还需要良好的可读性与美观性。

# 示例图表自定义
plt.figure(figsize=(10, 6)) # 设置图像尺寸
sns.scatterplot(data=df, x='x', y='y')
plt.title("这是一个带自定义样式的散点图", fontsize=16)
plt.xlabel("X轴标签", fontsize=12)
plt.ylabel("Y轴标签", fontsize=12)
plt.xticks(rotation=45) # X轴标签旋转45度
plt.grid(True, linestyle='–', alpha=0.5)
plt.tight_layout() # 自动调整子图间距
plt.show()


7. 图表保存与展示

# 保存图表到文件
plt.savefig("scatter_plot.png", dpi=300, bbox_inches='tight')
print("图表已保存为 scatter_plot.png")

# 展示图表
plt.show()

# 关闭当前图像释放内存
plt.close()


探索性数据分析流程示意图

以下Mermaid流程图展示了典型的EDA可视化流程:

#mermaid-svg-O3ukBtT2t90ttaKd{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-O3ukBtT2t90ttaKd .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-O3ukBtT2t90ttaKd .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-O3ukBtT2t90ttaKd .error-icon{fill:#552222;}#mermaid-svg-O3ukBtT2t90ttaKd .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-O3ukBtT2t90ttaKd .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-O3ukBtT2t90ttaKd .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-O3ukBtT2t90ttaKd .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-O3ukBtT2t90ttaKd .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-O3ukBtT2t90ttaKd .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-O3ukBtT2t90ttaKd .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-O3ukBtT2t90ttaKd .marker{fill:#333333;stroke:#333333;}#mermaid-svg-O3ukBtT2t90ttaKd .marker.cross{stroke:#333333;}#mermaid-svg-O3ukBtT2t90ttaKd svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-O3ukBtT2t90ttaKd p{margin:0;}#mermaid-svg-O3ukBtT2t90ttaKd .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-O3ukBtT2t90ttaKd .cluster-label text{fill:#333;}#mermaid-svg-O3ukBtT2t90ttaKd .cluster-label span{color:#333;}#mermaid-svg-O3ukBtT2t90ttaKd .cluster-label span p{background-color:transparent;}#mermaid-svg-O3ukBtT2t90ttaKd .label text,#mermaid-svg-O3ukBtT2t90ttaKd span{fill:#333;color:#333;}#mermaid-svg-O3ukBtT2t90ttaKd .node rect,#mermaid-svg-O3ukBtT2t90ttaKd .node circle,#mermaid-svg-O3ukBtT2t90ttaKd .node ellipse,#mermaid-svg-O3ukBtT2t90ttaKd .node polygon,#mermaid-svg-O3ukBtT2t90ttaKd .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-O3ukBtT2t90ttaKd .rough-node .label text,#mermaid-svg-O3ukBtT2t90ttaKd .node .label text,#mermaid-svg-O3ukBtT2t90ttaKd .image-shape .label,#mermaid-svg-O3ukBtT2t90ttaKd .icon-shape .label{text-anchor:middle;}#mermaid-svg-O3ukBtT2t90ttaKd .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-O3ukBtT2t90ttaKd .rough-node .label,#mermaid-svg-O3ukBtT2t90ttaKd .node .label,#mermaid-svg-O3ukBtT2t90ttaKd .image-shape .label,#mermaid-svg-O3ukBtT2t90ttaKd .icon-shape .label{text-align:center;}#mermaid-svg-O3ukBtT2t90ttaKd .node.clickable{cursor:pointer;}#mermaid-svg-O3ukBtT2t90ttaKd .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-O3ukBtT2t90ttaKd .arrowheadPath{fill:#333333;}#mermaid-svg-O3ukBtT2t90ttaKd .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-O3ukBtT2t90ttaKd .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-O3ukBtT2t90ttaKd .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-O3ukBtT2t90ttaKd .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-O3ukBtT2t90ttaKd .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-O3ukBtT2t90ttaKd .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-O3ukBtT2t90ttaKd .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-O3ukBtT2t90ttaKd .cluster text{fill:#333;}#mermaid-svg-O3ukBtT2t90ttaKd .cluster span{color:#333;}#mermaid-svg-O3ukBtT2t90ttaKd div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-O3ukBtT2t90ttaKd .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-O3ukBtT2t90ttaKd rect.text{fill:none;stroke-width:0;}#mermaid-svg-O3ukBtT2t90ttaKd .icon-shape,#mermaid-svg-O3ukBtT2t90ttaKd .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-O3ukBtT2t90ttaKd .icon-shape p,#mermaid-svg-O3ukBtT2t90ttaKd .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-O3ukBtT2t90ttaKd .icon-shape rect,#mermaid-svg-O3ukBtT2t90ttaKd .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-O3ukBtT2t90ttaKd .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-O3ukBtT2t90ttaKd .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-O3ukBtT2t90ttaKd :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}

加载数据集

单变量分析

数据分布是否正常?

双变量分析

数据清洗/变换

多变量分析

时间序列/文本分析

图表美化与输出

洞察总结与报告

单词与短语表(中英对照)

单词/短语音标词性词根/词缀释义搭配例句
histogram /ˈhɪstəɡræm/ n. histo-(组织)+ -gram(图) 直方图 draw a histogram We use a histogram to show the distribution of ages.
kdeplot /keɪ-diː-plɒt/ n. KDE(核密度估计)+ plot(图) 核密度估计图 create a kdeplot The kdeplot provides a smooth estimate of the probability density.
scatterplot /ˈskætəplɒt/ n. scatter(分散)+ plot(图) 散点图 plot a scatterplot A scatterplot reveals the relationship between two variables.
pairplot /ˈpeəplɒt/ n. pair(配对)+ plot(图) 散点图矩阵 generate a pairplot Seaborn’s pairplot is great for exploring correlations.
heatmap /ˈhiːtmæp/ n. heat(热)+ map(图) 热图 visualize with a heatmap The correlation heatmap uses color intensity to show strength.
boxplot /ˈbɒksplɒt/ n. box(箱)+ plot(图) 箱线图 interpret a boxplot A boxplot displays the median, quartiles, and outliers.
violinplot /vaɪəˈlɪnplɒt/ n. violin(小提琴)+ plot(图) 小提琴图 use a violinplot The violinplot combines a boxplot with a kernel density plot.
time series /ˈtaɪm ˈsɪəriːz/ n. time(时间)+ series(序列) 时间序列 analyze time series Time series analysis helps identify trends over time.
word cloud /wɜːd klaʊd/ n. word(词)+ cloud(云) 词云 generate a word cloud The word cloud highlights frequent terms in the text.

通过本指南,你可以系统掌握Python在探索性数据分析中的可视化工具与技巧。无论是单变量分布探查,还是多变量关系挖掘,或是时间序列与文本数据的可视化,合理运用这些图表工具将极大提升你的数据分析效率与洞察力。建议结合实际项目多加练习,形成自己的可视化工作流。

赞(0)
未经允许不得转载:171主机测评 » Python 数据可视化:从单变量到多变量
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址