python - 如何在 Pandas 中更轻松地绘制此 DataFrame
问题描述
这是我的数据框:
我用以下代码在 Pandas 中绘制了我的 df:
Armenia = [100.0, 21.943089, 23.344123]
Moldova = [100.0, 25.468598, 25.856620]
Ukraine = [100.0, 45.253380, 26.266646]
Vietnam = [100.0, 491.680706, 1083.782579]
Oman = [100.0, 277.381353, 659.887243]
Bangladesh = [100, 280.025959, 609.648111]
df = pd.DataFrame({'Vietnam' : Vietnam, 'Ukraine' : Ukraine, 'Bangladesh' : Bangladesh, 'Oman' : Oman,'Armenia': Armenia,'Moldova': Moldova}, index = ['1990', '2005', '2017'])
ax = df.plot.line(rot=0)
plt.title('Top 3 best and worst countries in combatting CO2 emission above 5 mt CO2', fontsize=14)
plt.xlabel('years', fontsize=14)
plt.ylabel('relative amount of CO2 emitted in %', fontsize=12)
plt.grid(True)
输出:
有没有更简单的方法来做到这一点?因为写入所有数据需要花费大量时间。
我非常感谢任何评论。谢谢!:)
解决方案
您的数据框是宽格式,所以我使用pd.melt
(文档)将其更改为长格式
我使用条形图绘制了测量结果,因为我认为您可以像这样更好地看到二氧化碳排放的演变。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
dic = {'country' : ['Vietnam', 'Oman', 'Bangladesh', 'Ukraine', 'Moldova', 'Armenia'],
'base' : [100.0, 100.0, 100.0, 100.0, 100.0, 100.0],
'RA05' : [491, 277, 280, 45, 25, 21],
'RA17' : [1083, 659, 609, 26, 25, 23]
}
df = pd.DataFrame(dic)
df_melted = pd.melt(df, id_vars='country', value_name='Value', var_name='Measurement')
print(df_melted)
Seaborn中的条形图版本:
ax = sns.barplot(data=df_melted, x='country', y='Value', hue='Measurement')
ax.set(xlabel='Country', ylabel='Relative amount of CO2 emitted in %', title='Top 3 best and worst countries in combatting CO2 emission above 5 mt CO2')
plt.show()
seaborn中的线图版本:
ax = sns.lineplot(data=df_melted, x='Measurement', y='Value', hue='country')
ax.set(xlabel='Year', ylabel='Relative amount of CO2 emitted in %', title='Top 3 best and worst countries in combatting CO2 emission above 5 mt CO2')
plt.show()
大熊猫的线图尝试。
df_melted.groupby('country')['Value'].plot(legend=True, marker='x', linestyle='--',
title='Top 3 best and worst countries in combatting CO2 emission above 5 mt CO2',
xticks=[], xlabel='years', ylabel='Relative amount of CO2 emitted in %')
推荐阅读
- redis - 如何在 Kubernetes 中为 redis 服务配置 envoy 边缘代理?
- javascript - 从按钮单击的父 div 内部获取元素和值
- android-studio - Android-studio 无法启动
- r - 我不知道如何在数据框中添加列“RICHNESS”,以及它的数据
- meteor - 困惑如何自定义流星验证邮件
- linux - 无法使用 apktool kali linux 重建 apk
- google-sheets - 如何在Google表格单元格中用空行查找和替换一个单元格中的子字符串
- discord.js - 用命令中的硬编码链接替换参数以播放音乐
- python - 使用 Scapy 发送带有随机偏移量的分片包
- python - JES Cipher 删除空格和标点符号