
数据可视化的概念
数据可视化使用统计图形,图表,信息图形和其他工具,来可视化复杂数据,以便于发现数据模式。这种可视化分析不仅应用于建模之前的数据分析阶段,在特征值分析和模型选择,模型性能分析等阶段也有积极的应用。
可视化分析的理论依据是人类大脑处理信息的方式,使用图表或图形对可大量复杂数据可视化处理比研究电子表格或报告更容易。数据可视化还有助于识别需要注意的区域,例如异常值,数据集中的不同聚类,等等。
数据可视化工具
流行的 Python 数据可视化软件包,包括 matplotlib,seaborn,等。常用的图形工具包括:
- 线图和点图 (Line Charts and Scatter Plots)
- 直方图 (Histgrams)
- 条形图 (Bar Charts)
- 颜*图色**(Heat Map)
线图和点图 (Line Charts and Scatter Plots)
在调用 seaborn 画图之前需要先加载软件包: import seaborn as sns。假设我们将数据加载到名为 df_data 的 DataFrame。执行以下的命令将 df_data 的所有列作线图, 同时设置图形的尺寸和标签 (title):
# Set the width and height of the figure
>>> plt.figure(figsize=(14,6))
# Add title
>>> plt.title("Demo of line plot")
# Plot
>>> sns.lineplot(data=df_data)
如果只是对数据的某些列作图,可以在 'data = df_data' 中指定 df_data 的列名。
点图的命令为:
# Set the width and height of the figure
>>> plt.figure(figsize=(14,6))
# Add title
>>> plt.title("Demo of scatter plot")
# Plot
>>> sns.scatterplot(x=df_data['x'], y=df_data['y'])
点图的命令中需要明确指定 x 和 y 的值。
直方图 (Histgrams)
直方图用于显示某一列数据的分布。在以下的 'sns.distplot()' 命令中,'a=' 用于选择直方图显示的内容,'kde=False' 是直方图的缺省项。
# Set the width and height of the figure
>>> plt.figure(figsize=(14,6))
# Add title
>>> plt.title("Demo of distribution plot")
# Plot
>>> sns.distplot(a=df_data['x'], kde=False)
和直方图相关的是分布密度图 (KDE: kernel density estimate),可以看作是光滑的直方图,命令行是:
>>> sns.kdeplot(data=df_data['x'], shade=True)
条形图 (Bar Charts)
条形图。在命令行 'sns.barplot' 中,需要定义水平的值x和垂直坐标的高度y。
# Set the width and height of the figure
>>> plt.figure(figsize=(14,6))
# Add title
>>> plt.title("Demo of bar chart")
# Plot
>>> sns.barplot(x=df_data.index, y=df_data['x'])
颜*图色**(Heat Map)
颜*图色**用颜色的深浅变化快速可视化数据的模式。下面的例子中可视化 DataFrame 中的所有数据,实际运用中也可以指定特定的列。
# Set the width and height of the figure
>>> plt.figure(figsize=(14,6))
# Add title
>>> plt.title("Demo of heat map")
# Plot
>>> sns.heatmap(data=df_data, annot=True)
选择不同的图形
以上介绍的图形可以归结为三类:
- 趋势图:线图是用于反映数据趋势的很好的选择。
- 关系图:用于反映数据中不同列之间关系的图型有很多选择。条形图可用于描述数据分组之间的关系;热图用颜色形象地反映数据中不同列之间的关系;散点图适用于描述较为连续的数据之间的相关性;散点图和颜色结合可以同时反映额外的类别变量的相关性。
- 统计分布图:直方图用于描述数据的离散统计分布;而 KDE 用于描述光滑的数据分布。