Python 数据可视化高级应用指南

1. 数据可视化基础

Python 的数据可视化主要通过 Matplotlib、Seaborn 和 Plotly 等库实现。

import matplotlib.pyplot as plt

# 简单的折线图
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

2. Matplotlib 高级应用

2.1 子图

import matplotlib.pyplot as plt
import numpy as np

# 创建子图
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

# 第一个子图
x = np.linspace(0, 10, 100)
y = np.sin(x)
axes[0, 0].plot(x, y)
axes[0, 0].set_title("Sine Wave")

# 第二个子图
y = np.cos(x)
axes[0, 1].plot(x, y)
axes[0, 1].set_title("Cosine Wave")

# 第三个子图
y = np.tan(x)
axes[1, 0].plot(x, y)
axes[1, 0].set_title("Tangent Wave")

# 第四个子图
y = np.exp(x)
axes[1, 1].plot(x, y)
axes[1, 1].set_title("Exponential Function")

plt.tight_layout()
plt.show()

2.2 样式定制

import matplotlib.pyplot as plt
import numpy as np

# 自定义样式
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, color='red', linestyle='--', linewidth=2, marker='o', markersize=5, label='Sin')
plt.plot(x, y2, color='blue', linestyle='-', linewidth=2, marker='s', markersize=5, label='Cos')

plt.title("Customized Plot", fontsize=16, fontweight='bold')
plt.xlabel("X-axis", fontsize=14)
plt.ylabel("Y-axis", fontsize=14)
plt.legend(fontsize=12, loc='upper right')
plt.grid(True, linestyle='--', alpha=0.7)

plt.show()

2.3 3D 图表

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# 创建 3D 图表
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# 生成数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))

# 绘制表面图
ax.plot_surface(x, y, z, cmap='viridis')

ax.set_title("3D Surface Plot")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")

plt.show()

3. Seaborn 高级应用

3.1 统计图表

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
np.random.seed(42)
data = np.random.normal(size=1000)

# 直方图
plt.figure(figsize=(10, 6))
sns.histplot(data, bins=30, kde=True)
plt.title("Histogram with KDE")
plt.show()

# 箱线图
data = [np.random.normal(size=100) for _ in range(3)]
plt.figure(figsize=(10, 6))
sns.boxplot(data=data)
plt.title("Box Plot")
plt.show()

# 小提琴图
plt.figure(figsize=(10, 6))
sns.violinplot(data=data)
plt.title("Violin Plot")
plt.show()

3.2 分类图表

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

# 生成数据
data = pd.DataFrame({
    'category': ['A', 'B', 'C', 'D'] * 25,
    'value': np.random.randn(100)
})

# 条形图
plt.figure(figsize=(10, 6))
sns.barplot(x='category', y='value', data=data)
plt.title("Bar Plot")
plt.show()

# 计数图
plt.figure(figsize=(10, 6))
sns.countplot(x='category', data=data)
plt.title("Count Plot")
plt.show()

# 点图
plt.figure(figsize=(10, 6))
sns.pointplot(x='category', y='value', data=data)
plt.title("Point Plot")
plt.show()

3.3 相关性分析

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

# 生成数据
np.random.seed(42)
data = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'z': np.random.randn(100)
})

# 散点图
plt.figure(figsize=(10, 6))
sns.scatterplot(x='x', y='y', data=data)
plt.title("Scatter Plot")
plt.show()

# 相关性热图
plt.figure(figsize=(10, 6))
corr = data.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.title("Correlation Heatmap")
plt.show()

# 配对图
plt.figure(figsize=(10, 6))
sns.pairplot(data)
plt.title("Pair Plot")
plt.show()

4. Plotly 高级应用

4.1 交互式图表

import plotly.express as px
import pandas as pd
import numpy as np

# 生成数据
np.random.seed(42)
data = pd.DataFrame({
    'x': np.linspace(0, 10, 100),
    'y': np.sin(np.linspace(0, 10, 100)),
    'z': np.cos(np.linspace(0, 10, 100))
})

# 交互式折线图
fig = px.line(data, x='x', y=['y', 'z'], title='Interactive Line Plot')
fig.show()

# 交互式散点图
fig = px.scatter(data, x='x', y='y', size='z', color='z', title='Interactive Scatter Plot')
fig.show()

# 交互式 3D 散点图
fig = px.scatter_3d(data, x='x', y='y', z='z', color='z', title='Interactive 3D Scatter Plot')
fig.show()

4.2 地理图表

import plotly.express as px

# 加载内置数据集
df = px.data.gapminder()

# 地理散点图
fig = px.scatter_geo(df[df['year'] == 2007], 
                     locations="iso_alpha", 
                     size="pop", 
                     color="continent", 
                     hover_name="country",
                     projection="natural earth",
                     title="World Population by Country (2007)")
fig.show()

#  choropleth 地图
fig = px.choropleth(df[df['year'] == 2007], 
                    locations="iso_alpha", 
                    color="lifeExp", 
                    hover_name="country",
                    color_continuous_scale=px.colors.sequential.Plasma,
                    title="Life Expectancy by Country (2007)")
fig.show()

4.3 仪表板

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np

# 创建子图
fig = make_subplots(rows=2, cols=2, subplot_titles=('Line Plot', 'Bar Plot', 'Histogram', 'Scatter Plot'))

# 生成数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 添加图表
fig.add_trace(go.Scatter(x=x, y=y1, name='Sin'), row=1, col=1)
fig.add_trace(go.Bar(x=[1, 2, 3, 4, 5], y=[10, 20, 30, 40, 50], name='Bar'), row=1, col=2)
fig.add_trace(go.Histogram(x=np.random.randn(1000), name='Histogram'), row=2, col=1)
fig.add_trace(go.Scatter(x=np.random.randn(100), y=np.random.randn(100), mode='markers', name='Scatter'), row=2, col=2)

# 更新布局
fig.update_layout(height=600, width=800, title_text="Dashboard")
fig.show()

5. 实际应用场景

5.1 股票分析

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

# 下载股票数据
ticker = "AAPL"
data = yf.download(ticker, start="2023-01-01", end="2023-12-31")

# 绘制收盘价
plt.figure(figsize=(12, 6))
plt.plot(data['Close'])
plt.title(f"{ticker} Closing Price")
plt.xlabel("Date")
plt.ylabel("Price")
plt.grid(True)
plt.show()

# 绘制成交量
plt.figure(figsize=(12, 6))
plt.bar(data.index, data['Volume'])
plt.title(f"{ticker} Volume")
plt.xlabel("Date")
plt.ylabel("Volume")
plt.grid(True)
plt.show()

# 绘制移动平均线
data['MA50'] = data['Close'].rolling(window=50).mean()
data['MA200'] = data['Close'].rolling(window=200).mean()

plt.figure(figsize=(12, 6))
plt.plot(data['Close'], label='Close')
plt.plot(data['MA50'], label='MA50')
plt.plot(data['MA200'], label='MA200')
plt.title(f"{ticker} Moving Averages")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.grid(True)
plt.show()

5.2 销售数据分析

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

# 生成销售数据
np.random.seed(42)
dates = pd.date_range('2023-01-01', '2023-12-31', freq='D')
sales = np.random.randn(365) * 100 + 1000
products = ['A', 'B', 'C'] * 121 + ['A'] * 2

 data = pd.DataFrame({
    'date': dates,
    'sales': sales,
    'product': products
})

# 按月份汇总
 data['month'] = data['date'].dt.month
monthly_sales = data.groupby('month')['sales'].sum().reset_index()

# 绘制月度销售
plt.figure(figsize=(12, 6))
sns.barplot(x='month', y='sales', data=monthly_sales)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()

# 按产品汇总
product_sales = data.groupby('product')['sales'].sum().reset_index()

# 绘制产品销售
plt.figure(figsize=(12, 6))
sns.pie(x='sales', y='product', data=product_sales, autopct='%1.1f%%')
plt.title("Product Sales Distribution")
plt.show()

# 绘制销售趋势
plt.figure(figsize=(12, 6))
sns.lineplot(x='date', y='sales', hue='product', data=data)
plt.title("Sales Trend by Product")
plt.xlabel("Date")
plt.ylabel("Sales")
plt.show()

5.3 数据科学分析

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_iris

# 加载数据集
iris = load_iris()
data = pd.DataFrame(data=iris.data, columns=iris.feature_names)
data['target'] = iris.target
data['target_name'] = data['target'].map({0: 'setosa', 1: 'versicolor', 2: 'virginica'})

# 绘制配对图
plt.figure(figsize=(12, 10))
sns.pairplot(data, hue='target_name')
plt.title("Iris Dataset Pair Plot")
plt.show()

# 绘制相关性热图
plt.figure(figsize=(10, 8))
corr = data.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.title("Iris Dataset Correlation Heatmap")
plt.show()

# 绘制箱线图
plt.figure(figsize=(12, 6))
sns.boxplot(data=data, orient='h')
plt.title("Iris Dataset Box Plot")
plt.show()

6. 最佳实践

  1. 选择合适的图表类型:根据数据类型和分析目的选择合适的图表类型。
  2. 数据预处理:在可视化之前对数据进行清洗和预处理。
  3. 图表定制:根据需要定制图表的样式、颜色、标签等。
  4. 交互性:对于复杂数据,使用交互式图表提高用户体验。
  5. 性能优化:对于大型数据集,使用适当的方法提高可视化性能。
  6. 文档化:为图表添加标题、标签和图例,提高可读性。
  7. 导出和分享:将图表导出为适当的格式,方便分享和展示。

7. 总结

Python 的数据可视化库提供了丰富的功能,从基本的折线图、柱状图到复杂的 3D 图表和交互式仪表板。通过掌握这些高级应用,我们可以更有效地分析和展示数据。

在实际应用中,数据可视化可以用于股票分析、销售数据分析、数据科学分析等多种场景,帮助我们更好地理解数据,做出更明智的决策。

希望本文对你理解和应用 Python 数据可视化有所帮助!

更多推荐