Plotly:如何向直方图添加文本标签?

Vaa*_*sha 7 python plotly plotly-express

有没有办法在 Plotly.Express 直方图中显示直方图聚合的计数值?

px.histogram(pd.DataFrame({"A":[1,1,1,2,2,3,3,3,4,4,4,5]}),x="A") 在此输入图像描述 如果我使用常规直方图,我可以指定text直接指向包含要显示的值的列的参数。

px.bar(pd.DataFrame({"val":[1,2,3,4,5], "height": [3,2,3,3,1]}), x="val", y="height", text="height") 在此输入图像描述

但对于直方图,该值是计算出来的,它甚至不是fig.to_dict(). 有没有办法将文本标签添加到直方图中?

使用下面的答案,我将这一发现总结为一篇文章 - https://towardsdatascience.com/histograms-with-plotly-express-complete-guide-d483656c5ad7

小智 8

text_auto设置为的参数将True执行您想要的操作。

以您的示例代码为例,这就是我得到的:

fig = px.histogram(pd.DataFrame({"A":[1,1,1,2,2,3,3,3,4,4,4,5]}),x="A", 
text_auto=True)
fig.show()
Run Code Online (Sandbox Code Playgroud)

作为新成员,我还无法嵌入屏幕截图,但这里有一个链接。

直方图

有点晚了但希望这会有所帮助。


ves*_*and 3

据我所知,绘图直方图没有文本属性。事实证明,如果可能的话,检索应用的 x 和 y 值并将它们放入适当的注释中也是很复杂的。您最好的选择似乎是使用numpy.histogram处理分箱并使用go.Bar. 下面的代码片段将产生以下图:

在此输入图像描述

完整代码:

import numpy as np
import plotly.express as px
import plotly.graph_objects as go

# sample data
df = px.data.tips()

# create bins
bins = [0, 10, 20, 30, 40, 50]
counts, bins = np.histogram(df.total_bill, bins=bins)
#bins2 = 0.5 * (bins1[:-1] + bins2[1:])

fig = go.Figure(go.Bar(x=bins, y=counts))
fig.data[0].text = counts
fig.update_traces(textposition='inside', textfont_size=8)
fig.update_layout(bargap=0)


fig.update_traces(marker_color='blue', marker_line_color='blue',
                  marker_line_width=1, opacity=0.4)

fig.show()
Run Code Online (Sandbox Code Playgroud)