Legend color does not match graph color

For a histogram of given random variable X, I I graph the kernal density estimation along with the correct histogram of the given sample, where the histogram has the transparency of 0.5.

I want my legend to reflect my color choice. But instead, it shows me the color of my KDE.

How do you match the 0.5 transparency, and the given color, to the legend?

Hi @plotmaster422,

could you provide the code for this chart and let us know, which colors do you want to be matched?

I assume you are plotting two traces, right?

Yes, using the generic histogram function from go.Figure(), then a scatterplot on on top of that - here is my code

ff = go.Figure()
ff.add_trace(go.Histogram({"histfunc": "count", "x": continuous, "histnorm": "probability density",
                           "opacity": 0.7, "marker": {"color": "rgba(4, 217, 255, 255)"}}, name=continuous.name.title() + "  "))
ff.add_trace(go.Scatter({"x": density, "y": pdf, "mode": "lines", "marker": {"color": "rgba(4, 217, 255, 255)"},
                         "showlegend": False}))

Ideally, color should be rgba(4, 217, 255, 0.7), but it shows up with an alpha of one.

Could you please provide a MRE?


  1. In your scatter trace you should set line_color, not marker_color, because you have mode="lines"!!!

  2. I suspect that you are perceiving a difference in color, because you have a black background for the plot, and a white one for the legend.
    This is an example that also has a black legend background:

import numpy as np
import plotly.graph_objects as go
from scipy.stats import norm

x = np.random.normal(1, 1.2, size=300)
X=   np.linspace(1-3*1.2, 1+3*1.2, 100)
mypdf=norm.pdf(X, loc=1, scale=1.2)

fig =go.Figure(go.Histogram(x=x, histfunc="count", histnorm= "probability density",
                           opacity= 0.7, marker_color= "rgba(4, 217, 255, 255)", 
fig.add_scatter(x=X, y=mypdf, mode="lines", line_color="rgba(4, 217, 255, 255)")
fig.update_layout(width=700, height=400, plot_bgcolor="black", yaxis_showgrid=False, yaxis_zeroline=False,  bargap=0.01, legend_bgcolor="black")

1 Like

Hello empet, you were right. it was an optical illusion from dark mode. colors were, in truth, both the same. legend stays unchanged.

Thank you!