Use YYYY-MM as X-axis

How can i adjust the x-axis ?

My code

import plotly.offline as pyo
import plotly.graph_objs as go
import pandas as pd
import datetime as dt
data = {‘date’:[‘2022-01’, ‘2022-02’, ‘2022-03’, ‘2022-04’], ‘val1’:[20, 21, 19, 18], ‘val2’:[2, 51, 16, 18]}
df = pd.DataFrame(data)
trace1 = go.Bar(
x=df[‘date’], # NOC stands for National Olympic Committee
y=df[‘val1’],
)
trace2 = go.Bar(
x=df[‘date’],
y=df[‘val2’],
)

data = [trace1, trace2]
layout = go.Layout(
title=‘some title’,
barmode=‘stack’
)
fig = go.Figure(data=data, layout=layout)
fig.update_layout(xaxis=dict(tickformat=“%Y-%m”))
pyo.plot(fig, filename=‘bar1.html’)

HI @marvy ,

I don’t understand your question. Your code produces the desired date format, doesen’t it?

yes but it show two time the same date ?

Now I see. I converted your df.date to datetime with

df.date = pd.to_datetime(df.date)

and then added the tickvals:

fig.update_layout(xaxis=dict(tickformat='%Y-%m', tickvals=df.date))

Full code:

import plotly.graph_objs as go
import pandas as pd

data = {'date':['2022-01', '2022-02', '2022-03', '2022-04'], 'val1':[20, 21, 19, 18], 'val2':[2, 51, 16, 18]}
df = pd.DataFrame(data)
df.date = pd.to_datetime(df.date)

trace1 = go.Bar(
x=df['date'], # NOC stands for National Olympic Committee
y=df['val1'],
)
trace2 = go.Bar(
x=df['date'],
y=df['val2'],
)

data = [trace1, trace2]
layout = go.Layout(
title='some title',
barmode='stack'
)
fig = go.Figure(data=data, layout=layout)
fig.update_layout(xaxis=dict(tickformat='%Y-%m', tickvals=df.date))

creates:


mrep ticks