Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

seaborn: How to add a second level of labels on the X axis

I need to plot a time series. Dates on the X axis and values on the Y axsis, but I also need to specify the day of week on the X axsis.

ax = sns.lineplot(x='date', y='value', data=df)

I expect to be able to add day of week (another column from df) on the X axis. example with Excel

like image 652
Diego Avatar asked Sep 06 '25 03:09

Diego


1 Answers

You can try to do this by adding a second x-axis. Please find below a code you'll need to adapt to your problem. I guess there are better ways to do that but it should works.

from matplotlib.ticker import MultipleLocator
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

x = np.arange(1000)
x2 = np.arange(1000)*2
y = np.sin(x/100.)

fig = plt.figure()

ax = plt.subplot(111)
sns.lineplot(x, y)
plt.xlim(0, 1000)
ax.xaxis.set_major_locator(MultipleLocator(200))

ax2 = ax.twiny()
sns.lineplot(x2, y, visible=False)
plt.xlim(0, 2000)
ax2.xaxis.set_major_locator(MultipleLocator(400))
ax2.spines['top'].set_position(('axes', -0.15))
ax2.spines['top'].set_visible(False)
plt.tick_params(which='both', top=False)

enter image description here

like image 167
TVG Avatar answered Sep 07 '25 16:09

TVG