brunorosilva / plotly-calplot

The easiest and best looking Calendar Heatmap you'll find, made with Plotly.
https://pypi.org/project/plotly-calplot/
104 stars 10 forks source link

Custom ticks for the second year #35

Open iitylerdurden opened 4 months ago

iitylerdurden commented 4 months ago

I am trying to include the total counts next to the month's names however I am struggling to make calplot to carry on with ticks for the second year as it starts the ticks array again from 0. Is there anything I can do to achieve what I am after?

image


def create_calplot(df, x='ds', y='value', title='', colorscale='aggrnyl'):
    """Create the calplot figure"""

    # Generate a complete range of dates for the desired period (one year back from today)
    end_date = datetime.today().date()
    start_date = end_date - timedelta(days=365)
    start_date = start_date.replace(month=1, day=1)
    date_range = pd.date_range(start=start_date, end=end_date)

    # Convert date column to datetime and ensure only dates
    df[x] = pd.to_datetime(df[x]).dt.date

    # Create a dataframe with all dates and merge with the original dataframe
    complete_df = pd.DataFrame(date_range, columns=[x])
    complete_df[x] = complete_df[x].dt.date
    complete_df = complete_df.merge(df, on=x, how='left')

    # Fill NaN values
    complete_df[y].fillna(0, inplace=True)

    # Create a new column for year-month
    complete_df['year_month'] = pd.to_datetime(complete_df[x]).dt.to_period('M')

    # Calculate the number of returns for each year-month
    month_counts = complete_df.groupby('year_month')[y].sum()

    # Prepare month names with counts
    month_names_with_counts = [f"{month.strftime('%B %Y')} ({month_counts.iloc[i]})" for i, month in enumerate(pd.period_range(start=start_date, end=end_date, freq='M'))]

    # Create the calplot figure
    fig = calplot(
        data=complete_df,
        x=x,
        y=y,
        colorscale=colorscale,
        month_lines_width=1.3,
        month_lines_color='black',
        title=title
    )

    fig.update_xaxes(
        tickmode='array',
        ticktext=month_names_with_counts,
        tickangle=0,
    )

    fig.update_layout(
        paper_bgcolor='rgba(0,0,0,0)',
        plot_bgcolor='rgba(0,0,0,0)',
        xaxis=dict(
            showgrid=False,
            zeroline=False,
            tickangle=0
        ),
        yaxis=dict(
            showgrid=False,
            zeroline=False
        )
    )

    return dcc.Graph(figure=fig, id='heatcal')```