Hovertext bug using discrete colour data on stacked bar chart with customdata
See original GitHub issueI 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 bug 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:
I would try and fix this myself via a pull request, but I’m struggling to get my head round the architecture of the module (esp. how it integrates with JS).
I have additionally reported this bug on StackOverflow and community.plotly.com
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
PS: thanks for the original, very detailed and clear issue! 😃
You’ve figured it out, yes! Basically Plotly Express takes care of splitting your data into multiple traces if needed, so the best way to use
customdata
is to give that to PX and let it split for you rather than trying to “bolt it on” after the fact.Note that PX will in fact create multiple traces even with continuous color, e.g. if you use the
facet_row
orfacet_col
oranimation_frame
arguments so in general it’s best to pass custom data from the original PX call in all cases 😉