如何将大熊猫DataFrame的行全部绘制成线?

时间:2019-06-04 15:12:16

标签: pandas matplotlib

假设我们有以下数据框:

import pandas as pd
df = pd.DataFrame(
         [
             ['Norway'     , 'beta', 30.0 , 31.0, 32.0, 32.4, 32.5, 32.1],
             ['Denmark'    , 'beta', 75.7 , 49.1, 51.0, 52.3, 50.0, 47.9],
             ['Switzerland', 'beta', 46.9 , 44.0, 43.5, 42.3, 41.8, 43.4],
             ['Finland'    , 'beta', 29.00, 29.8, 27.0, 26.0, 25.3, 24.8],
             ['Netherlands', 'beta', 30.2 , 30.1, 28.5, 28.2, 28.0, 28.0],
         ],
         columns = [
             'country',
             'run_type',
             'score A',
             'score B',
             'score C',
             'score D',
             'score E',
             'score F'
         ]
    )
df

如何将得分值绘制成线,其中每条线对应一个国家?

2 个答案:

答案 0 :(得分:1)

尝试绘制数据帧的转置:

# the score columns, modify if needed
score_cols = df.columns[df.columns.str.contains('score')]


df.set_index('country')[score_cols].T.plot()

输出:

![enter image description here

答案 1 :(得分:1)

由于您标记了matplotlib,因此这里是使用plt.plot()的解决方案。这个想法是使用iloc

逐行绘制线条
import matplotlib.pyplot as plt

# define DataFrame here

df1 = df.filter(like='score')

for i in range(len(df1)):
    plt.plot(df1.iloc[i], label=df['country'][i])

plt.legend()  
plt.show()

enter image description here