Home > OS >  Plotting for repeated values in Matplotlib and Python
Plotting for repeated values in Matplotlib and Python

Time:01-29

I have following set of data:

import pandas as pd
import matplotlib as mlp
import matplotlib.pyplot as plt 

nameLst = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
priceLst = [3, 1, 5, 2, 3, 6, 1, 8, 3]
dateLst = [1, 1, 1, 2, 2, 2, 3, 3, 3]
df = pd.DataFrame(columns = ['name', 'price', 'date'])
df['name'] = nameLst
df['price'] = priceLst
df['date'] = dateLst

name    price   date
0   a   3   1
1   b   1   1
2   c   5   1
3   a   2   2
4   b   3   2
5   c   6   2
6   a   1   3
7   b   8   3
8   c   3   3

And I want to create a seperate plot graphs for each name where x-axis contains date values and y-axis contains price values. I believe this code should do the work but I'm getting following error:

ValueError: The name date occurs multiple times, use a level number

Can you show me what I'm doing wrong?

for name, gp in df.groupby(['name']):
    fig, ax = plt.subplots()
    gp.pivot(index='date', columns='date', values='price').plot(ax=ax, marker='o', title=name)
    plt.show()

CodePudding user response:

If you want multiple subplots, one foe each name, in the same figure, the easiest way I am aware of is by using enter image description here


On the contrary, if you want a figure for each name, then you can do as @Mr. T explained in the comment to the question:

for name, gp in df.groupby(['name']):
    fig, ax = plt.subplots()
    gp.plot(x = "date", y = "price", ax = ax, marker = 'o', title = name)
    plt.show()

or by using an explicit filtering:

for name in df['name'].unique():
    df_tmp = df[df['name'] == name]
    fig, ax = plt.subplots()
    ax.plot(df_tmp['date'], df_tmp['price'])
    ax.set_title(name)
    plt.show()

CodePudding user response:

Building on Zephyr's answer, you can also use sns.relplot():

sns.relplot(data=df, kind='line', x='date', y='price', col='name')

Full code:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

nameLst = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
priceLst = [3, 1, 5, 2, 3, 6, 1, 8, 3]
dateLst = [1, 1, 1, 2, 2, 2, 3, 3, 3]
df = pd.DataFrame(columns = ['name', 'price', 'date'])
df['name'] = nameLst
df['price'] = priceLst
df['date'] = dateLst

sns.relplot(data=df, kind='line', x='date', y='price', col='name')

plt.show()

enter image description here

  •  Tags:  
  • Related