Plotly.py错误,在带有条形文字的customdata的堆叠条形图上使用离散颜色数据 我的代码中断的原因解决方案为什么连续颜色数据没有发生这种情况

问题描述

我有一个Pandas DataFrame df,我正在使用它填充Plotly条形图。为了示例,我们将df定义如下:

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","1"],"a": [1,2,4],"b": [1,4,9,16],"c": [1,8,27,64]
    }
)

并根据这些数据创建条形图

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()

错误出现在红色堆叠栏的悬停文本中。您会注意到,悬停文本中的xy数据是正确的,但是customdata产生的数据却不正确!

Discrete colour data causes customdata to be out of order

有趣的是,仅当传递给Pandas.Series的{​​{1}}参数的color对象由字符串数据(即离散颜色数据)组成时,才会发生此错误。如果在上面的代码中我改为设置px.bar()(使用整数表示连续的颜色数据,请注意颜色栏),将创建以下图形:

Continuous colour data workaround

我的项目需要使用离散的颜色数据,此错误是否有解决方法

最初在https://community.plotly.com/t/bug-using-bar-chart-categoryorder-and-customdata/43925?fbclid=IwAR2yKnSgedDjDmIGe3vhd8GPiQ_DFFAGephrq6G4Wl80iJST3Psn6kkzIs8询问

,随后在https://github.com/plotly/plotly.py/issues/2716

询问

解决方法

事实证明,解决方案相对简单,是我的错,而不是源代码本身的问题(哦,以为这不是我的错!)

我的代码中断的原因

在运行px.bar()时,plotly.express创建一个plotly.graph_objs.Figure对象,其中包含两个 Bar对象,而不是一个。然后,当调用fig.update_traces()时,会将customdata应用于Bar的子对象fig all 。 Red Eric Idle是原始DataFrame的第4个值,但是fig.update_traces()不在乎Red Eric Idle 使用的位置-它只知道现在是第二个{{1 }}对象。实际上,Red Eric Idle是此Bar对象的第一个数据点,因此快乐分配使用Barcustomdata[0][n]customdata[1][n]和{{1} }(第一个值),而不是我期望的customdata[2][n](第四个值)。

是为什么Red Eric Idle的悬停文本包含n=0而不是n=3的原因。

解决方案

解决方案非常简单。由于Plotly图“忘记了”在原始数据帧中每个点的数据在运行完"a: 1,b: 1,c: 1"之后应该移到的位置,因此我们只需为遗忘前的每个数据点 指定自定义数据(即在"a: 4,b: 16:,c: 64"通话期间。只需替换

px.bar()

使用

px.bar()

嘿,请记住,Red Eric Idle突然用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 = px.bar( df,barmode="stack",custom_data=["a","b","c"] ) fig = fig.update_traces( patch={ "hovertemplate": "x: %{x},c: %{customdata[2]}" },overwrite=True ) 悬停了文字:

Expected hover text behaviour is restored

这首先也是更整洁的代码。在原始的Plotly示例文档中,对我而言,4,16,64可以在1,1,1模块中这样分配并不明显。

为什么连续颜色数据没有发生这种情况

但是为什么在设置custom_data时这种奇怪的行为消失了?

原因是当plotly.express传递连续的颜色数据时,每个图形仅创建一个df.colour = [0,1]对象。在这种情况下,px.bar()中的每个数据点都会记住其在DataFrame中的行位置,因此Bar的分配就像一个超级按钮一样。