how to display only the dates in the list with plotly

Viewed 493

I have a dictionary of dates and values. I want to plot the dates in the x-axis and the values as the frequency for a bar graph. I am using the plotly library for plotting. Here is the dictionary

dic = {'2019-07-08': 2617.46,
 '2019-07-10': 834.85,
 '2019-07-12': 7473.66,
 '2019-07-14': 2613.32,
 '2019-07-16': 1704.76,
 '2019-07-17': 5093.44,
 '2019-07-18': 5261.57,
 '2019-07-20': 2680.4,
 '2019-07-21': 2649.23,
 '2019-07-22': 2707.12,
 '2019-07-23': 3700.2,
 '2019-07-25': 1914.86,
 '2019-07-26': 10084.15,
 '2019-07-27': 3523.5,
 '2019-07-28': 4210.9,
 '2019-07-29': 3671.15,
 '2019-07-30': 5537.15,
 '2019-07-31': 2478.58,
 '2019-08-01': 2466.83,
 '2019-08-02': 1003.85,
 '2019-08-03': 2509.84,
 '2019-08-04': 1442.77,
 '2019-08-05': 2505.77,
 '2019-08-06': 2585.98,
 '2019-08-07': 3615.0,
 '2019-08-08': 3485.0,
 '2019-08-09': 2545.11,
 '2019-08-10': 5385.89,
 '2019-08-11': 5066.72,
 '2019-08-12': 1613.13,
 '2019-08-14': 5214.57,
 '2019-08-17': 5016.14,
 '2019-08-18': 2516.5,
 '2019-08-20': 5018.91,
 '2019-08-21': 5219.65,
 '2019-08-23': 6003.43,
 '2019-08-24': 2883.58,
 '2019-08-28': 2096.97,
 '2019-08-31': 5005.5,
 '2019-09-12': 10944.4,
 '2019-09-14': 8262.22,
 '2019-09-15': 7346.34,
 '2019-09-16': 28577.43,
 '2019-09-23': 13014.43,
 '2019-09-25': 15606.88,
 '2019-09-28': 12157.82,
 '2019-09-30': 39007.12,
 '2019-10-03': 38652.59}

I want to plot this using plotly. This is my code

fig = px.bar(x=list(dic.keys()), y=list(dic.values()))
fig.update_xaxes(tickangle=90, tickvals = list(dic.keys()))
fig.update_layout(height=500, title_text="Frequency by date")

fig.show()

This is the result of the code enter image description here

How do I get rid of the gaps in the x-axis and only show the dates that are there in the dictionary?

1 Answers

You can create a dataframe with the dictionary. use the strtftime to display the dates as strings. This should solve your issue.

import pandas as pd

df = pd.DataFrame()
df['date'] = list(dic.keys())
df['values'] = list(dic.values())
df = df.set_index('date')

fig = px.bar(x=pd.to_datetime(df.index).strftime("%d/%m/%Y"), y=_df['values'])
fig.update_layout(height=500, width=1150, title_text="Frequency by date")

fig.show()

Hopefully this helps

enter image description here

Related