crf
crf

Reputation: 1880

Changing the marker according to some factor in a pandas time series plot

Suppose I have a pandas DataFrame like this

df = pd.DataFrame(
    {'data':[1, 2, 3, 4, 5], 'group': [-1, 0, 1, 0, -1]}, 
    index=pd.date_range('2014-01-01', periods=5)
)

I would like to plot a time series of df.data where the marker varies according to df.group. Is there a straightforward way to do this using df.plot()? If not, what is a simple way to do it?

Upvotes: 1

Views: 493

Answers (2)

Ajean
Ajean

Reputation: 5659

If fixing the dates and using seaborn as suggested by Paul H don't work out for you, here is a rather brute force way that makes use of groupby and pyplot's color cycle (although you can easily define your own color/marker cycle also).

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {'data':[1, 2, 3, 4, 5],
     'group': [-1, 0, 1, 0, -1]},
    index=pd.date_range('2014-01-01', periods=5))

fig, ax = plt.subplots()

nc = len(plt.rcParams['axes.color_cycle'])
for i, g in enumerate(df.groupby('group')):
    ax.scatter(g[1].index, g[1]['data'],
               color=plt.rcParams['axes.color_cycle'][i % nc])

fig.autofmt_xdate()
plt.show()

Resulting plot:

resulting plot

Upvotes: 1

Paul H
Paul H

Reputation: 68156

My first thought is to use seaborn, which is very good at this:

import numpy as np
import pandas
import seaborn
import matplotlib.pyplot as plt
%matplotlib inline

df = pandas.DataFrame({
    'data': [1, 2, 3, 4, 5], 
    'group': [-1, 0, 1, 0, -1]
},  index=pandas.date_range('2014-01-01', periods=5))
df

fgrid = seaborn.FacetGrid(df.reset_index(), hue='group')
fgrid.map(plt.plot, 'index', 'data', linestyle='none', marker='o')

The problem is that I can't get this to play nice with the fact that your x-axis values are dates.

enter image description here

Upvotes: 1

Related Questions