Joseoverflow
Joseoverflow

Reputation: 3

Incorrect label with groupby matplotlib

I have a plot and I would like to correct labels for plot lines:

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv('example.csv', parse_dates=['Date'],sep=';', 
dayfirst=True)
print(df)

data

car = df.Car.unique()


fig, ax = plt.subplots(3, sharex=True)

for ix, cars in enumerate(car):

    df[df['Car'] == cars].groupby(['Combustible']).plot(x='Date', 
                                  y='Cost', ax = ax[ix], 
                                  title="Cars: "+ cars, figsize=(10,8), 
                                 )

Plot

How can I display the correct label combustible by car? Is possible to plot without looping for, like ggplot face wrap function do?

Upvotes: 0

Views: 485

Answers (3)

Joseoverflow
Joseoverflow

Reputation: 3

I think I've found the best and simplest way:

g = sns.FacetGrid(df, row="Car", hue="Combustible", size=12)
g = g.map(plt.plot, "Date", "Cost")

Upvotes: 0

Joseoverflow
Joseoverflow

Reputation: 3

Using factorplot seaborn code is simpler:

sns.factorplot(x='Date', y = 'Cost', data=df, hue='Combustible', col="Car")

However, the performance is terrible! I have a dataframe with 85000 row and my computer can't plot it

Upvotes: 0

Alex Zisman
Alex Zisman

Reputation: 411

You can try this.

for ix, cars in enumerate(car):
    for l,g in df[df['Car'] == cars].groupby('Combustible'):
        g.plot(x='Date', label=l,
                                  y='Cost', ax = ax[ix],
                                  title="Cars: "+ cars, figsize=(10,8),
                                 )

enter image description here

Alternatively you can use seaborn and utilize the hue function

import seaborn as sns

for ix, cars in enumerate(car):
    p = sns.pointplot(x='Date',y='Cost',data=df[df['Car'] == cars], hue='Combustible', ax=ax[ix], figsize=(10,8))
    p.set_title('Cars: ' + cars)

enter image description here

Upvotes: 1

Related Questions