【问题标题】:How to plot this DataFrame easier in Pandas如何在 Pandas 中更轻松地绘制此 DataFrame
【发布时间】:2021-12-16 12:55:20
【问题描述】:

这是我的数据框:

我使用以下代码在 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)

输出:

有没有更简单的方法来做到这一点?因为写完所有的数据要花很多时间。

我真的很感激任何 cmets。谢谢! :)

【问题讨论】:

  • 写完所有数据要花很多时间你能澄清一下吗?
  • 好吧,因为目前只有 6 个国家有 3 个数据点,但想象一下如果这将有 20 个国家有 10 个数据点。必须有一个更通用的方法。我是熊猫和 python 的新手。
  • 所以你的问题不是绘图而是写数据,你从哪里得到数据?
  • 您是在询问关于灌封数据框还是创建数据框?
  • 来自:en.wikipedia.org/wiki/… 但我已经过滤、排序并将其选择到我自己的 DataFrame 中,如上所示

标签: python pandas numpy matplotlib plot


【解决方案1】:

您的数据框是宽格式,因此我使用 pd.melt (docs) 将其更改为长格式

我使用条形图绘制了测量值,因为我认为您可以像这样更好地看到二氧化碳排放的演变。

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)

Barplot 在 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()

Lineplot 在 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()

Lineplot 在 pandas 中的尝试。

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 %')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    相关资源
    最近更新 更多