Niam45
Niam45

Reputation: 578

Create plot of multiple lines taken from rows of dataframe

I would like to create a graph that plots multiple lines onto one graph.

Here is an example dataframe (my actual dataframe is much larger):

df = pd.DataFrame({'first': [1, 2, 3], 'second': [1, 1, 5], 'Third' : [8,7,9], 'Person' : ['Ally', 'Bob', 'Jim']})

The lines I want plotted are rowwise i.e. a line for Ally, a line for Jim and a line for Bob

Upvotes: 1

Views: 59

Answers (2)

mcsoini
mcsoini

Reputation: 6642

You can use the built-in plotting functions, as soon as the DataFrame has the right shape. The right shape in this case would be Person names as columns and the former columns as index. So all you have to do is to set Person as the index and transpose:

ax = df.set_index("Person").T.plot()
ax.set_xlabel("My label")

enter image description here

Upvotes: 1

JuR
JuR

Reputation: 123

First you should set your name as the index then retrieve the values for each index:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'first': [1, 2, 3], 'second': [1, 1, 5], 'Third' : [8,7,9], 'Person' : ['Ally', 'Bob', 'Jim']})
df = df.set_index('Person')

for person in df.index:
    val = df.loc[person].values
    plt.plot(val, label = person)
plt.legend()
plt.show()

enter image description here

As for how you want to handle the first second third I let you judge by yourself

Upvotes: 0

Related Questions