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)
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With