2

I have a plotly chart that looks like this:

enter image description here

Is there a way to make a second x axis that only has the years? What I mean is that I want two x axes: a 'sub-axis' that has the months (Sep, Nov, Jan , ...), and another one that has the years (2021, 2022, 2023).

Derek O
  • 16,770
  • 4
  • 24
  • 43
Cace
  • 31
  • 4

1 Answers1

0

It is possible to handle this by making the x-axis a multiple list, but if the original data is in date units, it will be changed to a graph of one day in month units. To put it more simply, if the data is for one year, there are 365 points, but if the data is displayed in months only, there will be 12 points. The closest way to meet the request is to make it month name and day.

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import calendar

df = px.data.stocks()
df['date'] = pd.to_datetime(df['date'])
df['year'] = df['date'].dt.year

multi_index = [df['year'].values,df['date'].dt.strftime('%b-%d').values]

fig = go.Figure()
fig.add_scatter(x=multi_index, y=df['GOOG'])

fig.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32