Randall Goodwin
Randall Goodwin

Reputation: 1976

Format datetime in seaborn faceted scatter plot

I am learning python pandas + matplotlib + seaborn plotting and data visualization from a "R Lattice" perspective. I am still getting my legs. Here is a basic question that I could not get to work just right. Here's the example:

# envir (this is running in an iPython notebook)
%pylab inline

# imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# generate some data
nRows = 500
df = pd.DataFrame({'c1' : np.random.choice(['A','B','C','D'], size=nRows),
               'c2' : np.random.choice(['P','Q','R'], size=nRows),
               'i1' : np.random.randint(20,50, nRows),
               'i2' : np.random.randint(0,10, nRows),
               'x1' : 3 * np.random.randn(nRows) + 90,
               'x2' : 2 * np.random.randn(nRows) + 89,
               't1' : pd.date_range('10/3/2014', periods=nRows)})

# plot a lattice like plot 
# 'hue=' is like 'groups=' in R
# 'col=' is like "|" in lattice formula interface

g = sns.FacetGrid(df, col='c1', hue='c2', size=4, col_wrap=2, aspect=2)
g.map(scatter, 't1', 'x1', s=20)
g.add_legend()

enter image description here

I would like the x axis to plot in an appropriate date time format, not as an integer. I am ok specify the format (YYYY-MM-DD, for example) as a start.

However it would be better if the time range was inspected and the appropriate scale was produced. In R Lattice (and other plotting systems), if the x variable is a datetime, a "pretty" function would determine if the range was large and implied YYYY only (say, for plotting 20 year time trend), YYYY-MM (for plotting something that was a few years)... or YYYY-MM-DD HH:MM:SS format for high frequency time series data (i.e. something sampled every 100 mS). That was done automatically. Is there anything like that available for this case?

One other really basic question on this example (I am almost embarrassed to ask). How can I get a title on this plot?

Thanks!
Randall

Upvotes: 2

Views: 2575

Answers (1)

Mike Williamson
Mike Williamson

Reputation: 3198

It looks like seaborn does not support datetime on the axes in lmplot yet. However, it does support with a few other of its plots. In the mean time, I would suggest adding your need to the issue in the link above, since it currently seems there isn't enough perceived need for them to address it.


As far as a title, use can use set_title() on the object itself. That would look something like this:

.
.
.
g = sns.FacetGrid(df, col='c1', hue='c2', size=4, col_wrap=2, aspect=2)
g.map(scatter, 't1', 'x1', s=20)
g.add_legend()

Then simply add:

g.set_title('Check out that beautiful facet plot!')

Upvotes: 1

Related Questions