数据可视化:Matplotlib 与 Seaborn

作者 : admin 本文共3754个字,预计阅读时间需要10分钟 发布时间: 2024-06-3 共1人阅读

数据可视化是数据分析中至关重要的一部分,它能帮助我们直观地理解数据的分布、趋势和关系。Python 中,Matplotlib 和 Seaborn 是两个最常用的可视化库。本文将详细介绍如何使用 Matplotlib 和 Seaborn 进行数据可视化,包括基本图形、图形定制、高级图形和实战案例等内容。

一、Matplotlib 基础

Matplotlib 是一个灵活而强大的绘图库,能够创建各种静态、动态和交互式图形。

1. 基本用法

import matplotlib.pyplot as plt # 简单的折线图 x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] plt.plot(x, y) plt.xlabel('X axis') plt.ylabel('Y axis') plt.title('Simple Line Plot') plt.show()

2. 图形定制
线条样式和颜色

plt.plot(x, y, linestyle='--', color='r', marker='o') plt.show()

子图
subplots(2, 2) axs[0, 0].plot(x, y, 'r') axs[0, 1].plot(x, y, 'g') axs[1, 0].plot(x, y, 'b') axs[1, 1].plot(x, y, 'y') plt.show()
3. 常见图表
柱状图

categories = ['A', 'B', 'C', 'D'] values = [3, 7, 5, 4] plt.bar(categories, values) plt.show()

散点图

x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6] y = [99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86] plt.scatter(x, y) plt.show()

直方图

data = [1.5, 2.5, 2.5, 3.5, 2.8, 4.2, 4.0, 5.5, 5.2, 4.8, 3.0, 4.0, 3.5, 2.5] plt.hist(data, bins=5) plt.show()

饼图

sizes = [15, 30, 45, 10] labels = ['A', 'B', 'C', 'D'] colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue'] explode = (0.1, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140) plt.axis('equal') plt.show()

二、Seaborn 基础

Seaborn 是基于 Matplotlib 之上的高级可视化库,专为统计图形而设计,能够生成更美观且信息丰富的图形。

1. 基本用法

import seaborn as sns # 设置主题 sns.set_theme() # 载入示例数据集 tips = sns.load_dataset("tips") # 创建一个简单的散点图 sns.scatterplot(x="total_bill", y="tip", data=tips) plt.show()

2. 常见图表
条形图

sns.barplot(x="day", y="total_bill", data=tips) plt.show()

箱线图

sns.boxplot(x="day", y="total_bill", data=tips) plt.show()

小提琴图

sns.violinplot(x="day", y="total_bill", data=tips) plt.show()

热力图

flights = sns.load_dataset("flights") flights_pivot = flights.pivot("month", "year", "passengers") sns.heatmap(flights_pivot, annot=True, fmt="d", cmap="YlGnBu") plt.show()

联合分布图

sns.jointplot(x="total_bill", y="tip", data=tips, kind="reg") plt.show()

三、Matplotlib 高级用法

1. 复杂图表
叠加图

x = range(1, 6) y1 = [1, 4, 6, 8, 10] y2 = [2, 2, 7, 10, 12] plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2') plt.legend() plt.show()

多子图

fig, axs = plt.subplots(2, 1) axs[0].plot(x, y1, 'tab:blue') axs[1].plot(x, y2, 'tab:orange') plt.show()

2. 动态图表

import matplotlib.animation as animation fig, ax = plt.subplots() x = [0] y = [0] line, = ax.plot(x, y) def update(frame): x.append(frame) y.append(frame ** 2) line.set_data(x, y) ax.relim() ax.autoscale_view() return line, ani = animation.FuncAnimation(fig, update, frames=range(10), blit=True) plt.show()

四、Seaborn 高级用法

1. FacetGrid

g = sns.FacetGrid(tips, col="time", row="sex") g.map(sns.scatterplot, "total_bill", "tip") plt.show()

2. PairGrid

g = sns.PairGrid(tips, hue="sex") g.map_diag(sns.histplot) g.map_offdiag(sns.scatterplot) g.add_legend() plt.show()

3. 自定义调色板

sns.set_palette("pastel") sns.boxplot(x="day", y="total_bill", data=tips) plt.show()

4. 风格设置

sns.set_style("whitegrid") sns.boxplot(x="day", y="total_bill", data=tips) plt.show()

五、实战案例:泰坦尼克号数据分析

在这个实战案例中,我们将使用 Matplotlib 和 Seaborn 来分析经典的泰坦尼克号乘客数据集。

1. 数据准备

import pandas as pd # 读取数据 titanic = sns.load_dataset("titanic") # 查看数据基本信息 print(titanic.info())

2. 数据预处理

# 填充缺失值 titanic['age'].fillna(titanic['age'].median(), inplace=True) titanic['embarked'].fillna(titanic['embarked'].mode()[0], inplace=True) titanic.drop(columns=['deck', 'embark_town', 'alive'], inplace=True)

3. 数据可视化
乘客年龄分布

plt.figure(figsize=(10, 6)) sns.histplot(titanic['age'], bins=30, kde=True) plt.title('Age Distribution of Passengers') plt.show()

各类舱乘客生还率

plt.figure(figsize=(10, 6)) sns.barplot(x='class', y='survived', data=titanic) plt.title('Survival Rate by Class') plt.show()

性别与生还率关系

plt.figure(figsize=(10, 6)) sns.barplot(x='sex', y='survived', data=titanic) plt.title('Survival Rate by Gender') plt.show()

年龄与生还率关系

plt.figure(figsize=(10, 6)) sns.violinplot(x='survived', y='age', data=titanic, split=True) plt.title('Age Distribution by Survival') plt.show()

结论

通过本文,我们深入了解了 Matplotlib 和 Seaborn 两个强大的 Python 可视化库的基础和高级用法。从基本图形的绘制到复杂图表和动态图表的创建,再到实际数据分析案例的应用,我们可以看到,Matplotlib 提供了灵活而强大的功能,Seaborn 则在统计图形方面更为便捷和美观。掌握这两个工具,将极大地提升我们在数据分析中的可视化能力。

参考文献

  1. Matplotlib 官方文档
  2. Seaborn 官方文档
  3. Pandas 官方文档
  4. 泰坦尼克号数据集
本站无任何商业行为
个人在线分享 » 数据可视化:Matplotlib 与 Seaborn
E-->