I have a Pandas DataFrame, df
which I am using to populate a Plotly bar chart. For the sake of example, let’s define df
as the following:
import pandas, numpy
import plotly.express as px
df = pandas.DataFrame.from_dict(
{
"x": ["John Cleese", "Eric Idle", "Michael Palin", "Eric Idle"],
"y": [7, 10, 3, 8],
"colour": ["0", "0", "0", "1"],
"a": [1, 2, 3, 4],
"b": [1, 4, 9, 16],
"c": [1, 8, 27, 64]
}
)
And create a bar chart derived from these data
fig = px.bar(df, x="x", y="y", color="colour", barmode="stack")
my_customdata = numpy.transpose(numpy.array([df["a"], df["b"], df["c"]]))
fig = fig.update_traces(
patch={
"customdata": my_customdata,
"hovertemplate": "x: %{x}, y: %{y}, a: %{customdata[0]}, b: %{customdata[1]}, c: %{customdata[2]}<extra></extra>"
},
overwrite=True
)
fig.update_layout(
xaxis={"categoryorder": "total ascending"}
)
fig.show()
The bug arises in the hover text for the red stacked bar. You’ll notice that the x
and y
data in the hover text are correct, but the data arising from the customdata
are not!
Intriguingly, this error only occurs when the Pandas.Series
object passed to the color
argument of px.bar()
consists of string data (i.e. discrete colour data). If in the code above I instead set df.colour = [0, 0, 0, 1]
(using integers for continuous colour data, notice the colorbar), the following graph is created:
My project requires the use of discrete colour data, is there a workaround for this bug?
Additionally posted at python - Plotly.py bug using discrete colour data on stacked bar chart with customdata in hover text - Stack Overflow