Home > Blockchain >  How to chose tick frequency on plotly.graph_objects.Heatmap date axis?
How to chose tick frequency on plotly.graph_objects.Heatmap date axis?

Time:11-04

The title really said it all, I have this plot of a dataframe with a datetime index with 1 row every 15 minutes a list of strings for columns and binary values in the cells:

fig = go.Figure(data=[
            go.Heatmap(x=df.columns,
                       y=df.index,
                       z=df.values,
                       colorscale=[[0, 'rgb(248,105,107)'], [1, 'rgb(99,190,123)']],
                       xgap=1,
                       ygap=1,
                       # yperiod = f'{1000*60*15}', #1000 milliseconds / second, 60 seconds per minute, 15 minutes per row.
                       showscale=False)
            ])
fig['layout']['yaxis']['autorange'] = "reversed" # earliest date on top, latest date down below.

Changing the value for yperiod doesn't change the number of periods, it only shifts them by a tiny little bit. The documentation calls for 'M' with in milliseconds between every y axis tick. If I use the M in the string the heatmap thinks I'm talking about months and I get a very long y axis.

Please help me get this to have 1 tick per row, it really shouldn't be very hard, nothing needs to be computed, just the index shown.

CodePudding user response:

Simulated a dataframe that I believe matches your structure. Have included four different parameters

  1. tick0 set to first time in index
  2. dtick work out number of milliseconds between first and second times in index
  3. reversed appears your code was trying to do this
  4. tickformat only want hours & minutes
import pandas as pd
import numpy as np
import plotly.graph_objects as go

S = 10
df = pd.DataFrame(
    index=pd.date_range("1-nov-2021", periods=S, freq="15min"),
    data=np.random.uniform(1, 100, [S, 5]),
    columns=list("ABCDE"),
)

fig = go.Figure(
    data=[
        go.Heatmap(
            x=df.columns,
            y=df.index,
            z=df.values,
            colorscale=[[0, "rgb(248,105,107)"], [1, "rgb(99,190,123)"]],
            xgap=1,
            ygap=1,
            # yperiod = f'{1000*60*15}', #1000 milliseconds / second, 60 seconds per minute, 15 minutes per row.
            showscale=False,
        )
    ]
)

fig.update_layout(
    yaxis={
        "tick0": df.index.min(),
        "dtick": (df.index[1] - df.index[0]).total_seconds() * 1000,
        "autorange": "reversed",
        "tickformat": "%H:%M",
    }
)

enter image description here

  • Related