问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Matplotlib和Seaborn数据可视化教程:从入门到实战

创作时间:
作者:
@小白创作中心

Matplotlib和Seaborn数据可视化教程:从入门到实战

引用
1
来源
1.
https://www.geeksforgeeks.org/plotting-with-seaborn-and-matplotlib/

Matplotlib和Seaborn是Python中两个最强大的数据可视化库。Matplotlib提供了低级、灵活的绘图方法,而Seaborn则通过内置主题和常见图表函数简化了绘图过程。

在开始绘图之前,请确保已经安装了这两个库:

pip install matplotlib seaborn

然后在脚本中导入它们:

import matplotlib.pyplot as plt
import seaborn as sns

使用Matplotlib进行基本绘图

Matplotlib允许使用plt.plot()创建简单的图表。下面是一个绘制线条和点的例子:

import matplotlib.pyplot as plt
plt.plot([0, 1], [10, 11], label='Line 1')
plt.plot([0, 1], [11, 10], label='Line 2')
plt.scatter([0, 1], [10.5, 10.5], color='blue', marker='o', label='Dots')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line and Dot Plot')
plt.legend()
plt.show()

解释:

  • plt.plot([0, 1], [10, 11], label='Line 1')绘制从(0,10)到(1,11)的上升线。
  • plt.plot([0, 1], [11, 10], label='Line 2')绘制从(0,11)到(1,10)的下降线。
  • label='Line 1' / 'Line 2'为图例分配名称。

为什么结合使用Matplotlib和Seaborn?

Seaborn使绘图更简单,但它是在Matplotlib基础上构建的,因此我们可以将两者结合使用以获得更好的效果:

  • 定制化:Matplotlib允许完全控制图表(轴、标签、网格、颜色等)。
  • 美观性:Seaborn具有内置主题和样式,使图表看起来更美观。
  • 统计图表:Seaborn包含特殊图表,如小提琴图和KDE图。
  • 灵活性:Matplotlib允许额外的定制和组合多个图表。

使用Seaborn风格增强Matplotlib

Seaborn通过内置主题和高级函数简化了数据可视化。

示例1:将Seaborn主题应用于Matplotlib图表

import matplotlib.pyplot as plt
import seaborn as sns
# 应用Seaborn主题
sns.set_theme(style="darkgrid")
# 创建一个简单的Matplotlib图表
x = [1, 2, 3, 4, 5]
y = [10, 12, 15, 18, 22]
plt.plot(x, y, marker='o', linestyle='-', color='blue', label="Trend")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Matplotlib Plot with Seaborn Theme")
plt.legend()
plt.show()

输出:

解释:

  • sns.set_theme(style="darkgrid")应用Seaborn主题以获得更清晰的外观。
  • 图表包含一个带有标记的简单线条,配有标签和图例。

示例2:使用Matplotlib自定义Seaborn图表

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
data = pd.DataFrame({
 'Year': [2018, 2019, 2020, 2021, 2022],
 'Sales': [100, 150, 200, 250, 300]
})
plt.figure(figsize=(8, 5))
sns.lineplot(x='Year', y='Sales', data=data, marker='o')
# 使用Matplotlib进行自定义
plt.title("Yearly Sales Growth", fontsize=14, fontweight='bold')
plt.xlabel("Year", fontsize=12)
plt.ylabel("Total Sales", fontsize=12)
plt.xticks(rotation=45)
plt.grid(True, linestyle='--')
plt.show()

输出:

解释:

  • Seaborn的sns.lineplot()从DataFrame创建线图。
  • Matplotlib函数自定义标题、轴标签和网格样式。

示例3:叠加Seaborn和Matplotlib图表

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.linspace(0, 10, 20)
y = np.sin(x)
plt.figure(figsize=(8, 5))
# Seaborn线图
sns.lineplot(x=x, y=y, color='blue', label='Sine Wave')
# Matplotlib散点图
plt.scatter(x, y, color='red', marker='o', label="Data Points")
plt.title("Seaborn Line Plot with Matplotlib Scatter Overlay")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()

输出:

解释:

  • sns.lineplot()创建平滑的正弦波。
  • plt.scatter()叠加红色数据点以增强可视化。

示例4:使用Matplotlib注释增强Seaborn直方图

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.randn(1000)
plt.figure(figsize=(8, 5))
sns.histplot(data, kde=True, bins=30, color='purple')
# 使用Matplotlib添加平均线
mean_value = np.mean(data)
plt.axvline(mean_value, color='red', linestyle='dashed', linewidth=2)
plt.text(mean_value + 0.1, 50, f'Mean: {mean_value:.2f}', color='red')
plt.title("Distribution with Seaborn and Matplotlib Customization")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()

输出:

解释:

  • sns.histplot()创建带有KDE曲线的直方图。
  • plt.axvline()在平均值处绘制虚线。
  • plt.text()在图上标注平均值。
© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号