怎样用Python案例实现数据可视化基础图表

访客 python案例 4

本文目录导读:

  1. 准备工作
  2. 折线图 - 展示趋势
  3. 柱状图 - 比较数据
  4. 散点图 - 展示相关性
  5. 饼图 - 展示占比
  6. 箱线图 - 展示数据分布
  7. 直方图 - 展示数据分布
  8. 热力图 - 展示相关性
  9. 综合案例 - 销售日报表
  10. 交互式图表(简单示例)
  11. 使用建议

我来用Python案例展示如何实现基础数据可视化图表,主要使用matplotlib和seaborn库。

准备工作

# 安装所需库
# pip install matplotlib seaborn pandas numpy
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 创建示例数据
np.random.seed(42)
data = pd.DataFrame({
    '月份': ['1月', '2月', '3月', '4月', '5月', '6月'],
    '销量': [120, 150, 180, 160, 200, 230],
    '利润': [30, 45, 60, 50, 70, 85],
    '产品': np.random.choice(['A', 'B', 'C'], 100),
    '销售额': np.random.normal(1000, 200, 100),
    '类别': np.random.choice(['电子产品', '服装', '食品'], 100)
})

折线图 - 展示趋势

# 折线图:展示数据随时间变化趋势
plt.figure(figsize=(10, 6))
plt.plot(data['月份'], data['销量'], marker='o', linewidth=2, markersize=8)
plt.plot(data['月份'], data['利润'], marker='s', linewidth=2, markersize=8)
'月度销售与利润趋势', fontsize=16)
plt.xlabel('月份', fontsize=12)
plt.ylabel('金额(万元)', fontsize=12)
plt.legend(['销量', '利润'])
plt.grid(True, alpha=0.3)
plt.show()

柱状图 - 比较数据

# 柱状图:比较不同类别的数据
plt.figure(figsize=(10, 6))
x = np.arange(len(data['月份']))
width = 0.35
plt.bar(x - width/2, data['销量'], width, label='销量')
plt.bar(x + width/2, data['利润'], width, label='利润')
'月度销售与利润对比', fontsize=16)
plt.xlabel('月份', fontsize=12)
plt.ylabel('金额(万元)', fontsize=12)
plt.xticks(x, data['月份'])
plt.legend()
plt.show()

散点图 - 展示相关性

# 散点图:展示两个变量之间的关系
plt.figure(figsize=(10, 6))
plt.scatter(data['销量'], data['利润'], s=100, alpha=0.7, c='blue')
# 添加趋势线
z = np.polyfit(data['销量'], data['利润'], 1)
p = np.poly1d(z)
plt.plot(data['销量'], p(data['销量']), "r--", alpha=0.8)
'销量与利润关系分析', fontsize=16)
plt.xlabel('销量(万元)', fontsize=12)
plt.ylabel('利润(万元)', fontsize=12)
plt.grid(True, alpha=0.3)
plt.show()

饼图 - 展示占比

# 饼图:展示各部分的占比
sales_by_category = data.groupby('类别')['销售额'].sum()
plt.figure(figsize=(8, 8))
plt.pie(sales_by_category.values, labels=sales_by_category.index, 
        autopct='%1.1f%%', startangle=90, colors=['#ff9999', '#66b3ff', '#99ff99'])
'各品类销售额占比', fontsize=16)
plt.axis('equal')
plt.show()

箱线图 - 展示数据分布

# 箱线图:展示数据分布和异常值
plt.figure(figsize=(10, 6))
plt.boxplot([data[data['类别'] == '电子产品']['销售额'],
             data[data['类别'] == '服装']['销售额']],
            labels=['电子产品', '服装'],
            patch_artist=True)
'不同品类销售额分布', fontsize=16)
plt.xlabel('产品类别', fontsize=12)
plt.ylabel('销售额(万元)', fontsize=12)
plt.grid(True, alpha=0.3)
plt.show()

直方图 - 展示数据分布

# 直方图:展示数据分布情况
plt.figure(figsize=(10, 6))
plt.hist(data['销售额'], bins=20, alpha=0.7, edgecolor='black', color='skyblue')
'销售额分布直方图', fontsize=16)
plt.xlabel('销售额(万元)', fontsize=12)
plt.ylabel('频数', fontsize=12)
plt.grid(True, alpha=0.3)
plt.show()

热力图 - 展示相关性

# 热力图:展示变量之间的相关性
correlation_matrix = data.select_dtypes(include=[np.number]).corr()
plt.figure(figsize=(8, 6))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0,
            square=True, linewidths=1, cbar_kws={"shrink": 0.8})
'变量相关性热力图', fontsize=16)
plt.show()

综合案例 - 销售日报表

# 综合案例:创建销售日报表仪表板
def create_sales_dashboard():
    # 创建多个子图
    fig, axes = plt.subplots(2, 3, figsize=(15, 10))
    # 1. 折线图 - 每日销售趋势
    hours = range(9, 22)
    hourly_sales = np.random.randint(50, 200, 13)
    axes[0, 0].plot(hours, hourly_sales, marker='o', color='blue')
    axes[0, 0].set_title('每小时销售趋势')
    axes[0, 0].set_xlabel('时间')
    axes[0, 0].set_ylabel('销售额')
    # 2. 柱状图 - 各部门销售
    depts = ['电子', '服装', '食品', '家居']
    dept_sales = [15000, 12000, 8000, 10000]
    axes[0, 1].bar(depts, dept_sales, color=['red', 'blue', 'green', 'orange'])
    axes[0, 1].set_title('部门销售额')
    # 3. 饼图 - 支付方式
    payments = ['微信', '支付宝', '现金', '银行卡']
    payment_amounts = [40, 35, 15, 10]
    axes[0, 2].pie(payment_amounts, labels=payments, autopct='%1.1f%%')
    axes[0, 2].set_title('支付方式占比')
    # 4. 散点图 - 客单价分布
    customer_ids = range(1, 51)
    unit_prices = np.random.normal(100, 30, 50)
    axes[1, 0].scatter(customer_ids, unit_prices, alpha=0.6)
    axes[1, 0].set_title('客单价分布')
    axes[1, 0].set_xlabel('客户编号')
    axes[1, 0].set_ylabel('客单价')
    # 5. 箱线图 - 各品类价格分布
    categories = ['A', 'B', 'C']
    prices = [np.random.normal(100, 20, 50) for _ in range(3)]
    axes[1, 1].boxplot(prices, labels=categories)
    axes[1, 1].set_title('品类价格分布')
    # 6. 显示关键指标
    axes[1, 2].axis('off')
    axes[1, 2].text(0.5, 0.8, '今日概要', fontsize=14, ha='center')
    axes[1, 2].text(0.5, 0.6, f'总销售额: ¥{sum(dept_sales):,}', ha='center')
    axes[1, 2].text(0.5, 0.4, f'订单数: 156', ha='center')
    axes[1, 2].text(0.5, 0.2, f'客单价: ¥{sum(dept_sales)/156:.2f}', ha='center')
    plt.tight_layout()
    plt.show()
# 运行仪表板
create_sales_dashboard()

交互式图表(简单示例)

# 使用matplotlib的交互功能
from matplotlib.widgets import Slider
plt.figure(figsize=(12, 6))
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 创建初始图形
l, = plt.plot(x, y, linewidth=2)'交互式正弦波')
plt.xlabel('x')
plt.ylabel('sin(x)')
# 添加滑块
ax_slider = plt.axes([0.2, 0.01, 0.65, 0.03])
slider = Slider(ax_slider, '频率', 0.1, 5.0, valinit=1)
# 更新函数
def update(val):
    freq = slider.val
    l.set_ydata(np.sin(freq * x))
    plt.draw()
slider.on_changed(update)
plt.grid(True)
plt.show()

使用建议

  1. 图表选择指南

    • 趋势展示:折线图
    • 比较数据:柱状图
    • 占比分析:饼图
    • 数据分布:直方图、箱线图
    • 相关性:散点图、热力图
  2. 美化技巧

    • 使用颜色调色板
    • 添加网格线
    • 调整字体大小
    • 添加数据标签
  3. 性能优化

    • 对于大数据集,使用seaborn或plotly
    • 缓存计算结果
    • 合理设置图表大小

这些案例涵盖了数据可视化的基础图表类型,你可以根据实际需求进行调整和组合。

标签: 折线图 柱状图

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