使用熊猫进行数据集的合并和可视化

时间:2018-09-09 10:11:30

标签: python pandas numpy matplotlib

例如,我清理了熊猫中的以下数据框并准备合并。

DataFrame1 for average Income per year

Country | Year 1  | Year 2  | Year 3
  A     |   50    |   30    |   20
  B     |   70    |   20    |   90
  C     |   10    |   20    |   30

Dataframe2 for Fertility rate 

Country | Year 1 | Year 2 | Year 3
   A    |   1.5  |   2    |  2.5
   B    |   2    |   2    |   3
   C    |   1    |   1    |   4 

基本上,我试图在matplotlib上显示多年来的DataFrame1和DataFrame2之间的关系。但是我似乎无法合并它们,因为它们的标题与Years相同?此外,当我尝试使用X轴作为年份时,我似乎无法找到一张图表来比较matplotlib上的这些数据。由于数据集非常庞大,因此任何建议都建议使用上述值作为即时消息。可能是数据太多了吗?

1 个答案:

答案 0 :(得分:0)

请考虑使用辅助轴生成单独的国家/地区图,因为您正在跟踪两个不同比例的度量标准:收入生育率。对于此设置,您将需要使用pandas.melt()将宽格式重整为长格式。然后,遍历各个国家/地区来过滤数据框。

数据

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df1 = pd.DataFrame({'Country': ['A', 'B', 'C'],
                    'Year 1': [50, 70, 10],
                    'Year 2': [30, 20, 20],
                    'Year 3': [20, 90, 30]})

df1 = df1.melt(id_vars='Country', value_name='Income', var_name='Year')

df2 = pd.DataFrame({'Country': ['A', 'B', 'C'],
                    'Year 1': [1.5, 2, 1],
                    'Year 2': [2.0, 2, 1],
                    'Year 3': [2.5, 3, 4]})

df2 = df2.melt(id_vars='Country', value_name='Fertility', var_name='Year')

情节

for c in df1['Country'].unique():
    fig, ax1 = plt.subplots(figsize=(10,4))

    ax2 = ax1.twinx()
    df1[df1['Country']==c].plot(kind='line', x='Year', y='Income', ax=ax1, color='g', legend=False)
    df2[df2['Country']==c].plot(kind='line', x='Year', y='Fertility', ax=ax2, color='b', legend=False)

    plt.title('Country ' + c)
    ax1.set_xlabel('Years')
    ax1.set_ylabel('Average Income Per Year')
    ax2.set_ylabel('Fertility Rate')

    lines = ax1.get_lines() + ax2.get_lines()
    ax1.legend(lines, [l.get_label() for l in lines], loc='upper left')

    ax1.set_xticks(np.arange(3))
    ax1.set_xticklabels(df1["Year"].unique())

    plt.show()
    plt.clf()

plt.close()

Plot Output

相关问题