1. Matplotlib
Matplotlib 是 Python 中最常用的数据可视化库之一,它提供了一个强大的绘图功能,可以生成各种静态、交互式图表。以下是对 Matplotlib 的详细解析:
1.1 安装与导入
pip install matplotlib
import matplotlib.pyplot as plt
1.2 基本图表
- 折线图
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.plot(x, y)
plt.show()
- 散点图
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.scatter(x, y)
plt.show()
1.3 高级功能
- 子图
fig, axs = plt.subplots(2, 1)
axs[0].plot(x, y)
axs[1].scatter(x, y)
plt.show()
- 颜色与样式
plt.plot(x, y, color='red', linestyle='--', marker='o')
plt.show()
2. Seaborn
Seaborn 是基于 Matplotlib 的另一个可视化库,它提供了更高级的图表和交互式功能。以下是 Seaborn 的详细解析:
2.1 安装与导入
pip install seaborn
import seaborn as sns
2.2 基本图表
- 箱线图
import numpy as np
data = np.random.normal(size=100)
sns.boxplot(data=data)
plt.show()
- 散点图
sns.scatterplot(x=x, y=y)
plt.show()
2.3 高级功能
- 热图
data = np.random.rand(10, 10)
sns.heatmap(data)
plt.show()
3. Plotly
Plotly 是一个交互式图表库,可以生成各种动态图表。以下是 Plotly 的详细解析:
3.1 安装与导入
pip install plotly
import plotly.graph_objs as go
3.2 基本图表
- 折线图
trace = go.Scatter(x=x, y=y, mode='lines+markers')
data = [trace]
layout = go.Layout(title='Line Chart', xaxis={'title': 'X Axis'}, yaxis={'title': 'Y Axis'})
fig = go.Figure(data=data, layout=layout)
fig.show()
- 散点图
trace = go.Scatter(x=x, y=y, mode='markers')
data = [trace]
layout = go.Layout(title='Scatter Plot', xaxis={'title': 'X Axis'}, yaxis={'title': 'Y Axis'})
fig = go.Figure(data=data, layout=layout)
fig.show()
4. Bokeh
Bokeh 是一个交互式可视化库,可以生成各种图表和地图。以下是 Bokeh 的详细解析:
4.1 安装与导入
pip install bokeh
from bokeh.plotting import figure, show
4.2 基本图表
- 折线图
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
p = figure(title="Line Chart", x_axis_label='X', y_axis_label='Y')
p.line(x, y, line_width=2)
show(p)
- 散点图
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
p = figure(title="Scatter Plot", x_axis_label='X', y_axis_label='Y')
p.scatter(x, y)
show(p)
5. Altair
Altair 是一个声明式可视化库,可以生成各种图表和地图。以下是 Altair 的详细解析:
5.1 安装与导入
pip install altair
import altair as alt
5.2 基本图表
- 折线图
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
chart = alt.Chart(data).mark_line(point=True).encode(
x='x',
y='y',
color='color'
).properties(
title='Line Chart'
)
chart.show()
- 散点图
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
chart = alt.Chart(data).mark_point().encode(
x='x',
y='y',
color='color'
).properties(
title='Scatter Plot'
)
chart.show()
以上是 Python 编程中五大热门数据可视化库的深度解析,希望对您有所帮助。
