Python可视化优化案例怎么写?

wen python案例 2

本文目录导读:

  1. 案例编写整体结构
  2. 完整的优化案例示例
  3. 高级优化技巧示例
  4. 案例编写模板
  5. 编写要点总结

我来详细说明如何编写Python可视化优化案例,并提供完整的示例代码和结构。

案例编写整体结构

标准案例框架

# 1. 问题描述
"""
问题:某电商平台用户购买行为分析
数据:1000个用户的年龄和消费金额
目标:优化图表展示,清晰呈现用户群体特征
"""
# 2. 导入库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 3. 生成/加载数据
np.random.seed(42)
data = pd.DataFrame({
    'age': np.random.randint(18, 60, 1000),
    'amount': np.random.normal(200, 100, 1000)
})
# 4. 优化前版本(基础版)
def plot_before(data):
    plt.figure(figsize=(8, 6))
    plt.scatter(data['age'], data['amount'])
    plt.title('用户消费分析')
    plt.show()
# 5. 优化后版本(优化版)
def plot_after(data):
    plt.figure(figsize=(12, 8))
    plt.scatter(data['age'], data['amount'], 
                alpha=0.6, c='steelblue', 
                edgecolors='white', linewidth=0.5)
    plt.xlabel('年龄', fontsize=12)
    plt.ylabel('消费金额(元)', fontsize=12)
    plt.title('用户消费行为分析', fontsize=16, fontweight='bold')
    # 添加趋势线
    z = np.polyfit(data['age'], data['amount'], 1)
    p = np.poly1d(z)
    plt.plot(data['age'], p(data['age']), 'r--', alpha=0.8)
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.show()

完整的优化案例示例

案例1:散点图优化

"""
案例:学生成绩分布可视化
优化点:颜色、大小、透明度、网格、图例
"""
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
np.random.seed(42)
math_scores = np.random.normal(75, 15, 200)
english_scores = np.random.normal(70, 20, 200)
# 优化前
def scatter_before():
    plt.figure(figsize=(8, 6))
    plt.scatter(math_scores, english_scores)
    plt.title('成绩分布')
    plt.show()
# 优化后
def scatter_after():
    plt.figure(figsize=(10, 8), dpi=100)
    # 计算密度
    from scipy.stats import gaussian_kde
    xy = np.vstack([math_scores, english_scores])
    z = gaussian_kde(xy)(xy)
    # 绘制散点图
    scatter = plt.scatter(math_scores, english_scores, 
                         c=z, s=50, alpha=0.7, 
                         cmap='viridis', edgecolors='white',
                         linewidth=0.5)
    plt.colorbar(scatter, label='密度')
    plt.xlabel('数学成绩', fontsize=12, fontweight='bold')
    plt.ylabel('英语成绩', fontsize=12, fontweight='bold')
    plt.title('学生成绩分布热力图', fontsize=16, fontweight='bold')
    plt.grid(True, alpha=0.3, linestyle='--')
    # 添加均值线
    plt.axhline(y=np.mean(english_scores), color='r', 
                linestyle='--', alpha=0.5, label='英语均值')
    plt.axvline(x=np.mean(math_scores), color='g', 
                linestyle='--', alpha=0.5, label='数学均值')
    plt.legend()
    plt.tight_layout()
    plt.show()
# 对比展示
def compare():
    plt.figure(figsize=(16, 6))
    plt.subplot(1, 2, 1)
    plt.scatter(math_scores, english_scores)
    plt.title('优化前')
    plt.subplot(1, 2, 2)
    xy = np.vstack([math_scores, english_scores])
    z = gaussian_kde(xy)(xy)
    plt.scatter(math_scores, english_scores, c=z, s=50, alpha=0.7, cmap='viridis')
    plt.title('优化后')
    plt.tight_layout()
    plt.show()

案例2:折线图优化

"""
案例:月度销售趋势分析
优化点:标注、图例、颜色、样式
"""
import pandas as pd
import matplotlib.pyplot as plt
# 生成数据
months = pd.date_range('2023-01-01', periods=12, freq='M')
sales = [120, 135, 128, 145, 160, 155, 170, 165, 180, 175, 190, 200]
# 优化前
def line_before():
    plt.figure(figsize=(8, 6))
    plt.plot(months, sales)
    plt.title('月度销售趋势')
    plt.show()
# 优化后
def line_after():
    plt.figure(figsize=(12, 6), dpi=100)
    # 主线条
    plt.plot(months, sales, marker='o', linewidth=2.5, 
             markersize=8, color='#2196F3', 
             markerfacecolor='white', markeredgecolor='#2196F3',
             markeredgewidth=2, label='实际销售')
    # 添加填充区域
    plt.fill_between(months, sales, alpha=0.1, color='#2196F3')
    # 标注关键点
    max_month = months[sales.index(max(sales))]
    max_sale = max(sales)
    plt.annotate(f'峰值: {max_sale}', xy=(max_month, max_sale),
                xytext=(max_month, max_sale + 10),
                arrowprops=dict(facecolor='black', arrowstyle='->'),
                fontsize=10, fontweight='bold')
    plt.xlabel('月份', fontsize=12, fontweight='bold')
    plt.ylabel('销售额(万元)', fontsize=12, fontweight='bold')
    plt.title('2023年月度销售趋势分析', fontsize=16, fontweight='bold')
    plt.grid(True, alpha=0.3, linestyle='--')
    plt.legend(loc='upper left')
    # 格式化x轴
    plt.gca().xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%Y-%m'))
    plt.gcf().autofmt_xdate()
    plt.tight_layout()
    plt.show()

案例3:柱状图优化

"""
案例:产品销量对比分析
优化点:颜色渐变、数值标签、排序
"""
# 优化后
def bar_optimized():
    categories = ['产品A', '产品B', '产品C', '产品D', '产品E']
    values = [85, 120, 95, 150, 110]
    # 排序
    sorted_idx = np.argsort(values)
    categories_sorted = [categories[i] for i in sorted_idx]
    values_sorted = [values[i] for i in sorted_idx]
    plt.figure(figsize=(10, 6), dpi=100)
    # 使用颜色渐变
    colors = plt.cm.Blues(np.linspace(0.3, 0.9, len(categories)))
    bars = plt.barh(categories_sorted, values_sorted, 
                   color=colors, edgecolor='white', linewidth=1.5)
    # 添加数值标签
    for i, (bar, v) in enumerate(zip(bars, values_sorted)):
        plt.text(v + 2, bar.get_y() + bar.get_height()/2, 
                f'{v}', ha='left', va='center', 
                fontsize=11, fontweight='bold')
    plt.xlabel('销售额(万元)', fontsize=12, fontweight='bold')
    plt.title('产品销量对比分析', fontsize=16, fontweight='bold')
    plt.grid(True, axis='x', alpha=0.3, linestyle='--')
    plt.tight_layout()
    plt.show()

高级优化技巧示例

1 交互式可视化

import plotly.express as px
import plotly.graph_objects as go
def interactive_plot():
    """使用Plotly创建交互式图表"""
    df = pd.DataFrame({
        'product': ['A', 'B', 'C', 'D'],
        'sales': [100, 150, 120, 180],
        'profit': [30, 45, 35, 55]
    })
    fig = px.scatter(df, x='sales', y='profit', 
                     text='product',
                     title='产品利润分析',
                     labels={'sales': '销售额', 'profit': '利润'})
    fig.update_traces(textposition='top center')
    fig.show()

2 分面图表

import seaborn as sns
def facet_plot():
    """使用Seaborn创建分面图表"""
    # 模拟多类别数据
    df = pd.DataFrame({
        'category': np.repeat(['A', 'B', 'C'], 100),
        'value': np.concatenate([
            np.random.normal(50, 10, 100),
            np.random.normal(60, 15, 100),
            np.random.normal(55, 12, 100)
        ]),
        'time': np.tile(pd.date_range('2023-01-01', periods=100, freq='D'), 3)
    })
    g = sns.FacetGrid(df, col='category', height=4, aspect=1.5)
    g.map(plt.plot, 'time', 'value', marker='.', linewidth=1)
    g.set_titles('类别 {col_name}')
    g.set_axis_labels('时间', '数值')
    plt.show()

3 动态展示优化效果

def before_after_comparison():
    """对比展示优化前后效果"""
    fig, axes = plt.subplots(1, 2, figsize=(14, 5))
    # 生成数据
    x = np.linspace(0, 10, 100)
    y = np.sin(x) + np.random.normal(0, 0.1, 100)
    # 优化前
    axes[0].plot(x, y, 'b-', alpha=0.7)
    axes[0].set_title('优化前', fontsize=14)
    # 优化后
    y_smooth = np.convolve(y, np.ones(5)/5, mode='valid')
    x_smooth = x[:len(y_smooth)]
    axes[1].plot(x, y, 'b-', alpha=0.3, label='原始数据')
    axes[1].plot(x_smooth, y_smooth, 'r-', linewidth=2, label='平滑处理')
    axes[1].fill_between(x, -1.5, 1.5, alpha=0.1, color='blue')
    axes[1].set_title('优化后', fontsize=14)
    axes[1].legend()
    plt.tight_layout()
    plt.show()

案例编写模板

"""
Python可视化优化案例模板
"""
class VisualizationOptimizer:
    def __init__(self, title="可视化优化案例"):
        self.title = title
        self.setup_style()
    def setup_style(self):
        """设置全局样式"""
        plt.style.use('seaborn-v0_8-whitegrid')
        plt.rcParams.update({
            'figure.facecolor': 'white',
            'axes.facecolor': '#f5f5f5',
            'font.size': 11,
            'axes.titlesize': 14,
            'axes.labelsize': 12,
        })
    def generate_data(self):
        """生成演示数据"""
        np.random.seed(42)
        return {
            'x': np.random.randn(100),
            'y': np.random.randn(100) * 2 + np.random.randn(100)
        }
    def create_before(self, data):
        """创建优化前版本"""
        plt.figure(figsize=(8, 6))
        plt.plot(data['x'], data['y'], 'o')
        plt.title(f'{self.title} - 优化前')
        return plt.gcf()
    def create_after(self, data):
        """创建优化后版本"""
        plt.figure(figsize=(10, 7), dpi=100)
        # 主要优化点
        plt.scatter(data['x'], data['y'], 
                   alpha=0.6, s=50, c='steelblue',
                   edgecolors='white', linewidth=0.5)
        # 添加回归线
        z = np.polyfit(data['x'], data['y'], 1)
        p = np.poly1d(z)
        x_sorted = np.sort(data['x'])
        plt.plot(x_sorted, p(x_sorted), 'r--', alpha=0.8, linewidth=2)
        # 添加置信区间
        from scipy import stats
        slope, intercept, r_value, p_value, std_err = stats.linregress(data)
        plt.fill_between(x_sorted, 
                        p(x_sorted) - 2*std_err,
                        p(x_sorted) + 2*std_err, 
                        alpha=0.1, color='red')
        plt.xlabel('X变量', fontsize=12, fontweight='bold')
        plt.ylabel('Y变量', fontsize=12, fontweight='bold')
        plt.title(f'{self.title} - 优化后', fontsize=14, fontweight='bold')
        plt.grid(True, alpha=0.3, linestyle='--')
        plt.tight_layout()
        return plt.gcf()
    def run_comparison(self):
        """运行对比展示"""
        data = self.generate_data()
        # 创建对比图
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
        # 优化前
        self.create_before(data)
        # 优化后
        self.create_after(data)
        plt.tight_layout()
        plt.show()
# 使用示例
if __name__ == "__main__":
    optimizer = VisualizationOptimizer("数据分析可视化优化")
    optimizer.run_comparison()

编写要点总结

优化维度清单

  1. 视觉层次:主次分明,突出关键信息
  2. 色彩运用:使用统一配色方案,避免过多颜色
  3. 信息和噪音:减少不必要的网格线、边框
  4. 可读性:合适的字体大小、标签清晰
  5. 交互性:考虑添加悬停提示、缩放等功能

最佳实践

# 1. 使用一致的样式
plt.style.use('seaborn-v0_8')
# 2. 选择合适的图表类型
# 数据关系 → 散点图、气泡图
# 趋势变化 → 折线图、面积图
# 对比分布 → 柱状图、箱线图
# 构成比例 → 饼图、堆积图
# 3. 添加必要的上下文
plt.xlabel('年龄', fontsize=12)
plt.ylabel('消费金额(元)', fontsize=12)'用户消费行为分析', fontsize=14, fontweight='bold')
# 4. 处理数据点重叠
plt.scatter(x, y, alpha=0.6, s=30)
# 5. 标注关键信息
plt.annotate('重要趋势变化', xy=(x_point, y_point),
             xytext=(x_point + 1, y_point + 1),
             arrowprops=dict(arrowstyle='->'))

这个案例编写指南涵盖了从基础到高级的优化技巧,你可以根据具体需求选择合适的案例模板进行修改和使用。

标签: 代码优化

抱歉,评论功能暂时关闭!