Bar plot in Plotly with constant spacing between random dates

Question:

I am trying to create a bar plot with px.bar from plotly.express with the following code:

px.bar(data_, x='DATE', y='Change')

DATE is a datetime column and my issue here is that I want constant spacing between dates i.e. I want the bars to side-by-side and not split out across the range of dates. Below is what I get with the above code:

enter image description here

What I want the bar plot to look like is this:

enter image description here

Where there is constant spacing between the bars.

Is there an input which will force the bars to stand side-by-side instead of being split out across the range from the minimum to maximum date?

Sample data:

0  2015-05-11   7.15
1  2015-05-12 -14.56
2  2015-06-19   2.18
3  2015-06-22 -12.73
4  2018-01-18  19.17
5  2020-03-16  -6.92
6  2020-03-17  -6.07
7  2020-03-18 -12.49
8  2020-03-19 -30.54
9  2020-03-20 -41.73
10 2020-03-23 -37.37
11 2020-03-24 -28.02
12 2020-03-25 -25.29
13 2020-03-26 -21.15
14 2020-04-02  -3.60
15 2021-05-19  -8.02
16 2021-05-20  -6.45
17 2021-06-04  -8.38
18 2021-06-07  -8.81
19 2021-06-08  -6.05
20 2021-06-10  -8.01
21 2022-02-28  -9.79
22 2022-03-09 -10.81
23 2022-06-14 -16.04
24 2022-06-15 -22.17
25 2022-06-16 -19.93
26 2022-06-17 -12.68
27 2022-08-05  15.76
28 2022-09-22  -4.23
29 2022-09-28  10.02
Asked By: Spedtsberg

||

Answers:

To simply arrange the bars, instead of setting the time series on the x-axis, for example, after specifying the index of the data frame, create and set a tick string for any x-axis; to create the x-axis string, add a column with only year data from the sample data, and replace duplicate years with blanks Created a list of ticks.

df['date'] = pd.to_datetime(df['date'])
df['year'] = df['date'].dt.year
ticktext = [x if not boolen else '' for x,boolen in zip(df['year'], df.duplicated('year', keep='first'))]

import plotly.graph_objects as go

fig = go.Figure(go.Bar(x=df.index, y=df['value']))

fig.update_xaxes(tickvals=df.index, ticktext=ticktext, tickangle=0)
fig.show()

enter image description here

Answered By: r-beginners
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.