Black Lives Matter. Please consider donating to Black Girls Code today.

Set Alignment of Vertical Bar on X axis

Hi I am trying to change where my bars start and stop on a bar chart. My goal is to have a bar that spans the entire month. right now my code is:

    cumulative = go.Bar(y=self.gb[self.y_column],
                        x=self.gb.index,
                        name='Cumulative',
                        hoverinfo='x+y',
                        hovertemplate="Month: %{x} <br>Cumulative Tank " + self.units + ": %{y}",
                        opacity=0.6,
                        marker=dict(color='rgb(158,202,225)',
                                    line=dict(color='rgb(8,48,107)',
                                              width=1.5,
                                              ),
                                    )
                        )

and my output is:

I currently have the xtick set at the end of the month. If I can make the bars right-aligned to the xtick I can use a custom bar width to make it reach the end of the month. I don’t think I can calculate the middle day of the month, because on months with 31 days I’ll have either a one day gap or be one day over. Any help would be greatly appreciated!

I also posted this on stackoverflow:https://stackoverflow.com/questions/56030852/set-alignment-for-plotly-bar-graph-x-axis

So I decided to implement a work around by using a filled line graph. here is the code, one helper function to calculate the monthly cumulative values and the plotly filled area scatter object:

def cumulative_df(df, date_term, y_term, v_print):
    v_print('Making the Monthly Sum DF')
    df = df[[date_term, y_term]]
    df = df.set_index(date_term)
    gb = df.groupby(pd.Grouper(freq="M")).sum()

    starts = []
    for index, row in gb.iterrows():
        new_start = index - pd.offsets.MonthBegin(1, normalize=True)
        starts.append([new_start, row.values[0]])

    starts_df = pd.DataFrame(starts, columns=[date_term, y_term])
    starts_df = starts_df.set_index(date_term)
    gb = gb.append(starts_df, sort=False)
    gb.sort_values(date_term, inplace=True)
    return gb

And the plotly call:

        cumulative = [go.Scatter(y=self.gb[self.y_column],
                                x=self.gb.index,
                                name='Cumulative',
                                hoverinfo='x+y',
                                hovertemplate="Month: %{x} <br>Cumulative Meter " + self.units + ": %{y}",
                                fill='tozeroy',
                                fillcolor=self.fill_color,
                                line={'color': self.cum_line_color,}
                                )]

        scatters = cumulative + scatters

And here’s the output:

I Would also welcome a Solution for this issue. I used to use matplotlib and it was possible to specify align=“left”, “right” or “center”