python plotly date axis as string not dates
Asked Answered
P

3

5

I want to create a bar chart using python plotly, with on the x-axis dates as strings/categories. For some reason, plotly keeps transforming strings to dates. My x-axis is continuous "timeline" of dates, rather than categories as I would expect.

My question: how can I construct a bar chart where my dates are handled as categories, rather than dates?

Minimal example:

d = {'date': ['2018-08-04', '2018-08-02','2018-08-03', '2018-08-11','2018-08-11'], 'score': [3, 4, 6, 2,8]}
df = pd.DataFrame(data=d)

data = [go.Bar(
            x=df['date'],
            y=df['score']
    )]

offline.iplot(data, filename='basic-bar')

Example:

enter image description here

Prolific answered 28/9, 2018 at 9:9 Comment(0)
C
5

You can specify the axis type in your layout settings. Plotly autodetects dates but you can overwrite it by setting type='category'.

enter image description here

import pandas as pd
import plotly

plotly.offline.init_notebook_mode()

d = {'date': ['2018-08-04', '2018-08-02','2018-08-03', '2018-08-11','2018-08-11'], 
     'score': [3, 4, 6, 2,8]}
df = pd.DataFrame(data=d)

data = plotly.graph_objs.Bar(x=df['date'],
                             y=df['score'])

#the magic happens here
layout = plotly.graph_objs.Layout(xaxis={'type': 'category'})

fig = plotly.graph_objs.Figure([data], layout)
plotly.offline.iplot(fig)
Cthrine answered 1/10, 2018 at 21:35 Comment(0)
L
3

Reading the documentation about date formatting and time series, it seems like plotly automatically converts data that is formatted as a date... to a date.

  1. You should reformat your data, such as '2018-08-04' becomes '2018/08/04' for instance. But you would have a more basic bar plot, meaning the X intervals wouldn't look as nicely formatted as it is now.

  2. You can always rename the x-axis manually, but it might be overkill for what you're trying to do. To do this, I suggest you do pd.date_range() so that you're getting a list of dates with plotly date format, then, manually set the x labels.

Lucrecialucretia answered 28/9, 2018 at 11:39 Comment(0)
S
0

Another way of doing this with plotly express.

import pandas as pd
import plotly.express as px

d = {'date': ['2018-08-04', '2018-08-02','2018-08-03', '2018-08-11','2018-08-11'], 'score': [3, 4, 6, 2,8]}

df = pd.DataFrame(data=d)

fig = px.bar(df, x='date', y='score')
fig.update_layout(xaxis=dict(type='category')) # type update to category
fig.show()
Stogner answered 25/3 at 17:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.