简体   繁体   English

Pandas DataFrame Plot:值列表

[英]Pandas DataFrame Plot: lists of values

I have a Pandas DataFrame which resembles: 我有一个类似的Pandas DataFrame:

pd.DataFrame({
    'el1': {
        'steps': [0,1,2], 
        'values': [10, 9, 8]
    },
    'el2': {
        'steps': [0,1,2], 
        'values': [1,  2, 8]
    },
    'el3': {
        'steps': [0,1,2], 
        'values': [5,  9, 4]
    }
})

        el1         el2         el3
steps   [0, 1, 2]   [0, 1, 2]   [0, 1, 2]
values  [10, 9, 8]  [1, 2, 8]   [5, 9, 4]

what would be the best way to try and use Panda's DataFrame plot to get some simple line plots with values on the y axis and steps on the x axis? 尝试使用Panda的DataFrame图来获取一些简单的线图的最佳方法是什么,这些线图的y轴上的valuesx轴上的steps (eg there should be three lines) (例如应该有三行)

Use matplotlib 使用matplotlib

c = ['r', 'g', 'b']
for i in range(df.shape[1]):
    plt.plot(df.iloc[0, i], df.iloc[1, i], c=c[i], label=df.columns[i])
plt.legend(df.columns)
plt.xlabel('Steps')
plt.ylabel('Values')
plt.show()

t

Here's a different construction. 这是另一种构造。 Largely because I'm more comfortable with transforming the underlying data frame first before plotting. 很大程度上是因为我对在绘制之前先转换基础数据框比较满意。 The plotting of the graph is pretty much the same so, credits go to @meW for the lines of code. 该图的绘制几乎相同,因此,代码行应归功于@meW。

import pandas as pd
import matplotlib.pyplot as plt


df = pd.DataFrame({
    'el1': {
        'steps': [0,1,2], 
        'values': [10, 9, 8]
    },
    'el2': {
        'steps': [0,1,2], 
        'values': [1,  2, 8]
    },
    'el3': {
        'steps': [0,1,2], 
        'values': [5,  9, 4]
    }
})

ndf = pd.DataFrame({v:df[v].values[1] for v in df.columns})
ndf.index = df.el1.steps
ndf.columns = df.columns

>>>ndf
   el1  el2  el3
0   10    1    5
1    9    2    9
2    8    8    4

plt.plot(ndf)
plt.legend(ndf.columns)
plt.xlabel('Steps')
plt.ylabel('Values')
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM