Search code examples
pythonvisualizationdataframeplotly

Plotly graph does not show x-axis values correctly


Consider the following code :

from plotly import graph_objs as go
import pandas as pd

mtds = ['2022-03', '2022-04', '2022-05', '2022-06']
values = [28, 24, 20, 18]

data1 = []
for j in range(4):
  data1.append([mtds[j], values[j]])
df1 = pd.DataFrame(data1, columns=['month', 'counts'])

fig = go.Figure()

fig.add_trace(go.Scatter(
   x = df1['month'],
   y = df1['counts'],
  name = 'counts history'
))

fig.show()

The output is

enter image description here

However, this is not was I was expecting. I would like to amend the code such that the mtds list string values '2022-03', '2022-04', '2022-05', '2022-06' are shown in the x-axis instead of the dates. Could you please assist with this ?

Thank you.


Solution

  • As per the plotly documentation on time series, you can use the update_xaxes method to change the ocurrence and format of the x-axis labels:

    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df1["month"], y=df1["counts"], name="counts history"))
    fig.update_xaxes(dtick="M1", tickformat="%Y-%m")
    fig.show()
    

    enter image description here