import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.graph_objects as go
df = pd.DataFrame(d) # use the data dict here
n_locations = df.location_encoded.nunique()
pivot_table = df.pivot_table(index='day', columns='time', values='location_encoded', aggfunc='first')
heatmap_data = pivot_table.values
x_labels = pivot_table.columns
y_labels = pivot_table.index
cmap = plt.get_cmap('viridis', n_locations)
color_map = [cmap(i) for i in range(n_locations)]
fig = go.Figure(data=go.Heatmap(
z=heatmap_data,
x=x_labels,
y=y_labels,
colorscale=[[i / (n_locations - 1), f"rgba{color_map}"] for i in range(n_locations)],
colorbar=dict(
tickvals=np.arange(n_locations),
title='Location'
),
))
fig.update_layout(
xaxis=dict(title='Time of Day'),
yaxis=dict(title='Date'),
title='Heatmap of Location Data',
)
fig.show()
В результате получается следующая тепловая карта:

Цветовая полоса справа теперь представляет собой непрерывную шкалу, но я хочу, чтобы она была дискретной, т. е. все локации имели свой цвет. В примерах на веб-сайте Plotly показано использование color_continous_scale, однако этот параметр доступен только для визуальных элементовplotly.express. Как можно сделать цветовую полосу дискретной для начала. Тепловая карта?
ОБНОВЛЕНИЕ:
Следующий код работает отлично (спасибо к комментариям):
# First we create a list of np.linspace values where each value repeats twice, except for the beginning (0) and the ending (1)
vals = np.r_[np.array(0), np.repeat(list(np.linspace(0, 1, self.n_locations+1))[1:-1], 2), np.array(1)]
# Then we make a list that contains lists of the values and the corresponding colors.
cc_scale = [[j, colors[i//2]] for i, j in enumerate(vals)]
# Create the heatmap using Plotly
self.fig = go.Figure(data=go.Heatmap(
z=self.heatmap_data,
x=x_labels,
y=y_labels,
colorscale=cc_scale,
colorbar=dict(
tickvals=np.linspace(1/self.n_locations/2, 1 - 1/self.n_locations/2, self.n_locations) * (self.n_locations - 1), # Center the ticks
ticktext=self.location_labels,
title='Location'
),
))
Подробнее здесь: https://stackoverflow.com/questions/771 ... ts-heatmap