Klaster
Klaster

Reputation: 683

Plotting Pandas: Grouped line chart

I have a pandas dataframe in the following format:

groups  value
1       0
0       0
0       0
0       0.1
1       0.4
1       0.5
0       0.5
1       0.8
0       0.8
1       0.9
1       1
1       1
1       1
1       1
0       1
0       1

I want a sorted line plot that has the value in the y-axis, as shown here:

example graph

Anyway: I also want a similar line for each group in the same plot as well. (Or JUST the two lines for the groups, but they differ in size)

Can anybody help me out? I reckon thats possible?

I use python 3.x with pandas 0.16.2. I'd prefer using matplotlib or seaborn.

Upvotes: 1

Views: 3027

Answers (1)

Jianxun Li
Jianxun Li

Reputation: 24742

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('/home/Jian/Downloads/real_data.csv')

# processing
# ==========================
fig, ax = plt.subplots()
ax.set_ylim([0, 1.2])
count = 0

def func(group):
    group.sort('value', inplace=True)
    x = np.linspace(0, 1, len(group))
    global ax, count
    if count > 0:
        ax.plot(x, group.value, label=group.groups.values[0])
    count += 1
    return group

df.groupby('groups').apply(func)
ax.legend(loc='best')

enter image description here

Upvotes: 3

Related Questions