首页 > 解决方案 > 如何在 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)

输出:

输出

有没有更简单的方法来做到这一点?因为写入所有数据需要花费大量时间。

我非常感谢任何评论。谢谢!:)

标签: pythonpandasnumpymatplotlibplot

解决方案


您的数据框是宽格式,所以我使用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 %')

在此处输入图像描述


推荐阅读