You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于groupby生成的DataFrame绘制指定规则Matplotlib双折线图

Matplotlib双折线图实现方案

你的数据集为Ethnicity、TOT Population二级索引结构,可按以下步骤实现指定可视化需求:

  • 首先重置索引拆分两类群体数据,注意两个群体的TOT Population数值差超过3个数量级(Hispanic群体为万级以下,Not Hispanic群体为千万级),严格按x轴=TOT Population、y轴=Years绘图会导致Hispanic群体折线集中在x轴最左侧,可视效果较差,以下同时提供需求严格匹配版本和常规统计可视化推荐版本。
  • 绘图前先配置Matplotlib中文显示(无中文需求可跳过),避免乱码问题。
  • 绘制折线后补充轴标签、图例、网格等元素优化可读性。

完整实现代码

import pandas as pd
import matplotlib.pyplot as plt

# 基础配置:解决中文显示问题,无中文需求可注释以下2行
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# ---------------------- 数据预处理 ----------------------
# 重置二级索引,将Ethnicity、TOT Population从索引转为普通列
df_process = df.reset_index()
# 拆分两类群体数据
df_hispanic = df_process[df_process['Ethnicity'] == 'Hispanic or Latino']
df_not_hispanic = df_process[df_process['Ethnicity'] == 'Not Hispanic or Latino']

# ---------------------- 版本1:严格匹配需求(x=TOT Population,y=Years) ----------------------
plt.figure(figsize=(12, 6))
# 绘制两条折线,添加标记点方便识别
plt.plot(df_hispanic['TOT Population'], df_hispanic['ID Year'], 
         label='Hispanic', color='#2E86AB', marker='o', linewidth=2)
plt.plot(df_not_hispanic['TOT Population'], df_not_hispanic['ID Year'], 
         label='Not Hispanic', color='#A23B72', marker='s', linewidth=2)
# 图表标注配置
plt.xlabel('TOT Population', fontsize=12)
plt.ylabel('Years', fontsize=12)
plt.title('两类群体总人口与年份对应关系', fontsize=14, pad=15)
plt.legend(fontsize=12)
plt.grid(alpha=0.3, linestyle='--')
plt.tight_layout()
plt.show()

# ---------------------- 版本2:推荐常规版本(x=Years,y=TOT Population,观察人口变化趋势) ----------------------
plt.figure(figsize=(12, 6))
# 按年份排序保证折线连接顺序正确
df_hispanic_sorted = df_hispanic.sort_values(by='ID Year')
df_not_hispanic_sorted = df_not_hispanic.sort_values(by='ID Year')

plt.plot(df_hispanic_sorted['ID Year'].astype(int), df_hispanic_sorted['TOT Population'], 
         label='Hispanic', color='#2E86AB', marker='o', linewidth=2)
plt.plot(df_not_hispanic_sorted['ID Year'].astype(int), df_not_hispanic_sorted['TOT Population'], 
         label='Not Hispanic', color='#A23B72', marker='s', linewidth=2)
# 解决量级差异问题:y轴设为对数刻度(可选)
# plt.yscale('log')
# 图表标注配置
plt.xlabel('Years', fontsize=12)
plt.ylabel('TOT Population', fontsize=12)
plt.title('两类群体总人口随年份变化趋势', fontsize=14, pad=15)
plt.legend(fontsize=12)
plt.grid(alpha=0.3, linestyle='--')
# x轴年份显示为整数
year_min = int(df_process['ID Year'].min())
year_max = int(df_process['ID Year'].max())
plt.xticks(range(year_min, year_max + 1))
plt.tight_layout()
plt.show()

可调参数说明

  • 折线样式:修改plot函数内color(颜色)、marker(点标记)、linewidth(线宽)参数即可自定义样式
  • 量级差异适配:如果需要同坐标系展示两个量级差异大的折线,取消plt.yscale('log')的注释即可使用对数y轴
  • 年份显示:如果ID Year列为浮点型,用.astype(int)转换即可避免x轴显示小数年份

内容的提问来源于stack exchange,提问作者eaglepien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 05:21:46