Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Date labels using Seaborn FacetGrid

Tags:

pandas

seaborn

I want to make a facet grid with variable names as the columns, and departments as the rows, and each small chart is a scatter chart of y=value and x=date

My data is sort of like this:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from datetime import datetime
import matplotlib.dates as mdates
import random

datelist = pd.date_range(start="march 1 2020", end="may 20 2020", freq="w").tolist()
varlist = ["x", "y", "z", "x", "y", "z", "x", "y", "z", "x", "y", "z"]
deptlist = ["a", "a", "b", "a", "a", "b", "a", "a", "b", "a", "a", "b"]
vallist =  random.sample(range(10, 30), 12)
df = pd.DataFrame({'date': datelist, 'value': vallist, 'variable': varlist, 'department': deptlist})

I want to make a facet grid with variable names as the columns, and departments as the rows, and each small chart is a scatter chart of y=value and x=date

Here is what I have so far. It almost works, except I want to see dates along the bottom that are not squished together, so I would like to see "3/1 4/1 5/1" instead of full dates. But I can't figure out how to format it.

plt.style.use('seaborn-darkgrid')
xformatter = mdates.DateFormatter("%m-%d")
g = sns.FacetGrid(df2, row="department", col="variable", sharey='row')
g = g.map(plt.plot, "date", "value", marker='o', markersize=0.7)
datelist = pd.date_range(start="march 1 2020", end="june 1 2020", freq="MS").tolist()
g.set(xticks=datelist)

enter image description here

This is pretty close, but notice the dates along the bottom x axes. They are all scrunched together. That's why I tried to use a special date formatter but couldn't get it to work. Really what I would like is that each date shows up as mon-dd and that I can control how many tick marks appear there.

like image 669
pitosalas Avatar asked Apr 30 '20 16:04

pitosalas


1 Answers

You can access the Axes object of the FacetGrid as g.axes (a 2D array). You could iterate over this array and change the properties of all the axes, but in your case you have sharex=True (the default), that means that changing the xaxis of one of the subplots will change all of the subplots at the same time.

g = sns.FacetGrid(df, row="department", col="variable", sharey='row')
g = g.map(plt.plot, "date", "value", marker='o', markersize=0.7)

xformatter = mdates.DateFormatter("%m/%d")
g.axes[0,0].xaxis.set_major_formatter(xformatter)

enter image description here

like image 65
Diziet Asahi Avatar answered Oct 27 '22 10:10

Diziet Asahi