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

如何使用Matplotlib从CSV文件生成折线图并展示多列数据及英国甲烷排放可视化故障解决

解决Matplotlib折线图异常及多国数据扩展方案

看起来你的折线图显示异常大概率是年份数据类型不对或者数据未按年份排序导致的,同时我也会给你一套适配后续添加多国数据的模块化写法,方便对比各国趋势。

一、先修复当前英国数据的折线图问题

首先,你的代码里漏了import pandas as pd(虽然你说脚本能运行,但显式导入能避免潜在隐患),然后核心问题可能出在这两点:

  1. 年份列可能是字符串格式,Matplotlib会把它当作离散分类值,导致折线无法正确呈现趋势
  2. 数据没有按年份升序排列,折线会乱序显示甚至看起来像“单条线”

修改后的单国家代码如下:

import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model  # 暂时用不到可先注释

# 读取数据并预处理
df = pd.read_csv(r'C:\Users\avalo\Desktop\Data.csv')
# 确保年份是数值类型(兼容原数据是字符串的情况)
df.iloc[:, 0] = pd.to_numeric(df.iloc[:, 0], errors='coerce')
# 按年份升序排序
df = df.sort_values(by=df.columns[0])

# 提取数据
X = df.iloc[:, 0].values
Y = df.iloc[:, 1].values

# 绘制折线图(添加label方便后续扩展图例)
plt.plot(X, Y, color='darkblue', label='UK')
plt.title("Levels of Methane (CH4) Emissions (Tonnes)")
plt.xlabel("Years")
plt.ylabel("Number of Tonnes")
plt.legend()  # 显示图例
plt.show()

二、适配多国数据的扩展方案

后续添加其他国家数据时,建议把CSV改成长格式结构(更易维护),示例格式如下:

Year,Country,Methane_Tonnes
2015,UK,120000
2016,UK,115000
2015,France,95000
2016,France,92000

如果你的CSV是宽格式(每列对应一个国家,比如Year,UK,France,...),可以用pd.melt转成长格式。然后用以下代码批量绘制多国折线:

import pandas as pd
import matplotlib.pyplot as plt

# 读取长格式数据
df = pd.read_csv(r'C:\Users\avalo\Desktop\Multi_Country_Data.csv')
# 确保年份是数值类型并排序
df['Year'] = pd.to_numeric(df['Year'], errors='coerce')
df = df.sort_values(by='Year')

# 自定义各国对应颜色(后续新增国家直接在这里加即可)
country_colors = {
    'UK': 'darkblue',
    'France': 'darkred',
    'Germany': 'darkgreen',
    'USA': 'gold'
}

# 循环绘制每个国家的折线
for country in df['Country'].unique():
    country_data = df[df['Country'] == country]
    plt.plot(country_data['Year'], country_data['Methane_Tonnes'], 
             color=country_colors.get(country, 'gray'),  # 未定义颜色的国家用灰色兜底
             label=country)

plt.title("Methane (CH4) Emissions by Country (Tonnes)")
plt.xlabel("Years")
plt.ylabel("Number of Tonnes")
plt.legend(title='Countries')  # 给图例添加标题
plt.grid(alpha=0.3)  # 可选:添加网格线提升可读性
plt.show()

这样后续新增国家时,只需要在CSV里补充数据,再在country_colors字典里新增对应颜色即可,非常便捷。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 11:42:33