Bar Chart - Dates Shown as Months on X Axis

Hi, I have two fields I want plotted on a bar chart, a date field (ā€˜Inbound Dateā€™) and the count of inbound leads.

I want to show the counts in terms of months on the bar chart, however when I try to plot this, I just get a bar chart of all the dates (understandably). I think then tried to create another column translating the date to the Month Name. I then tried to plot the month name and the aggregated counts, however the x axis ordered the months alphabetically when I need them ordered by calendar month.

Here is my code. Is there anyway I can plot the dates but have them shown as month aggregates? Or a way where I can change the order of the x axis if I plot the Month column instead?

df_sv = df.copy()

df_sv = df_sv.groupby(['Inbound Date', 'Business Type'], as_index=False).count()

df_sv = df_sv.sort_values(by='Inbound Date', ascending=True)

types = ['HVAC', 'Family Law']
data = []

for x in types:
    df_aux = df_sv[df_sv['Business Type']==x]
    data.append(
        go.Bar(
            x=df_aux['Inbound Date'],
            y=df_aux['Quarter'],
            name = x
    )
    )

layout = go.Layout(
    xaxis = dict(
        tickformat= '%b'
    )
)

fig = go.Figure(data = data, layout = layout)

py.iplot(fig, filename='basic-bar')

Hi @SitaraAbraham,

Iā€™m not sure I understand the structure of the data youā€™re working with. Setting xaxis.tickformat to '%b' like you have should cause the abbreviated month name to be displayed for each axis tick. Are you getting too many tick marks? If so, you can set xaxis.tickvals to an array of the exact dates where you want the tick marks to appear.

If that doesnā€™t help, could you include some sample data and a screen shot of what youā€™re seeing?

-Jon

What do you mean ā€œto an array of the exact dates where you want the tick marks to appearā€?

I set the tickformat to %b, but to your point now the dates appear as month names, but there are too many ā€œmonthā€ ticks. I would like them to be aggregated into 1 month tick per month if that makes sense.

Hi @SitaraAbraham,

Hereā€™s an example

import pandas as pd
import plotly.graph_objs as go
fig = go.FigureWidget()

dates = pd.date_range('2018-01', '2018-12', freq='MS')
fig.add_bar(x=dates, y=[2, 3, 4, 1, 4, 5, 3, 4, 5, 3, 2, 3])

fig.layout.xaxis.tickvals = pd.date_range('2018-01', '2018-12', freq='MS')
fig.layout.xaxis.tickformat = '%b'
fig

Hope that helps,
-Jon

1 Like