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

使用Python绘制共享x轴双y轴折线图统计年地震次数与产油量

问题诊断与实现方案

核心错误原因

你的代码存在三个核心问题,也是报错和图表不符合预期的原因:

  • 未做聚合统计:直接传入行级原始数据绘图,没有按年份统计地震次数和产油总量,逻辑不符合需求
  • 数据类型错误:test_data2的BBLS字段带千位分隔符逗号,为字符串类型,matplotlib无法将其识别为数值绘制,是你遇到TypeError的直接原因
  • 数据未对齐:test_data1和test_data2的行数量、年份分布不一致,直接传入数据会导致两个折线x轴点无法对齐,图表混乱

完整实现代码

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

# 1. 预处理地震数据:统计1980年起每年地震次数
test_data1['year'] = test_data1['year'].astype(int)
quake_year_count = test_data1[test_data1['year'] >= 1980]\
                    .groupby('year')['place'].count()\
                    .reset_index(name='quake_count')

# 2. 预处理注入井数据:统计1980年起每年总产油桶数
# 处理BBLS字段千位分隔符,转换为数值类型
test_data2['BBLS'] = test_data2['BBLS'].str.replace(',', '').astype(int)
test_data2['Year'] = test_data2['Year'].astype(int)
oil_year_sum = test_data2[test_data2['Year'] >= 1980]\
                .groupby('Year')['BBLS'].sum()\
                .reset_index(name='total_bbls')

# 3. 对齐两个数据集的年份,保证x轴完全匹配
merge_df = pd.merge(quake_year_count, oil_year_sum, 
                    left_on='year', right_on='Year', 
                    how='inner')

# 4. 绘制共享x轴的双y轴折线图
fig, ax1 = plt.subplots(figsize=(12,6))

# 左侧y轴:年地震次数
ax1.plot(merge_df['year'], merge_df['quake_count'], color='r', label='年地震次数')
ax1.set_xlabel('年份')
ax1.set_ylabel('年地震次数', color='r')
ax1.tick_params(axis='y', labelcolor='r')

# 右侧y轴:年总产油桶数
ax2 = ax1.twinx()
ax2.plot(merge_df['year'], merge_df['total_bbls'], color='b', label='年总产油桶数')
ax2.set_ylabel('年总产油桶数', color='b')
ax2.tick_params(axis='y', labelcolor='b')

# 合并显示图例
fig.legend(loc="upper right", bbox_to_anchor=(0.95, 0.95))
plt.title('1980年起年地震次数与年总产油桶数趋势')
plt.show()

代码说明

  • 预处理阶段统一了两个数据集的年份格式为整数,处理了BBLS字段的格式问题,保证数值可用于绘图
  • 聚合阶段分别按年份做了计数、求和运算,筛选出1980年及以后的统计结果
  • 绘图前做了数据集合并,保证两个折线的x轴年份完全对齐,避免绘图错位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 11:36:04