如何在plotly中创建彩色直方图?

问题描述 投票:0回答:1

我正在尝试弄清楚如何使用plotly构建带有类似于下图的颜色条的直方图。

enter image description here

plotly histogram colorbar
1个回答
0
投票
import numpy as np
import plotly.express as px
import plotly.graph_objects as go

mu, sigma = 100, 50  # mean and standard deviation
s = np.random.normal(mu, sigma, 1000)

# question shows a funky color scale...
color_scale = [
    c
    for c in zip(
        np.linspace(0, 0.5, len(px.colors.sequential.Blues[1:])),
        px.colors.sequential.Blues[1:][::-1],
    )
] + [
    c
    for c in zip(
        np.linspace(0.5, 1, len(px.colors.sequential.Reds[1:])),
        px.colors.sequential.Reds[1:],
    )
]

# use numpy to generate histogram
y, x = np.histogram(s, bins=30)
# bin edges to midpoint
x = [(a + b) / 2 for a, b in zip(x, x[1:])]
px.bar(x=x, y=y, color=x, color_continuous_scale=color_scale).update_traces(
    marker_line_color="black"
).update_layout(bargap=0, coloraxis_cmid=mu)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.