密谋:如何在直方图中添加文本标签? 完整代码:

问题描述

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

px.histogram(pd.DataFrame({"A":[1,1,2,3,4,5]}),x="A")

enter image description here

如果我要使用常规的直方图,则可以指定text参数,该参数直接指向包含要显示的值的列。

px.bar(pd.DataFrame({"val":[1,5],"height": [3,1]}),x="val",y="height",text="height")

enter image description here

但是对于直方图,此值是计算得出的,甚至不属于fig.to_dict()的一部分。有没有一种方法可以将文本标签添加到直方图中?

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

解决方法

据我所知,绘图直方图没有text属性。事实也证明,如果完全可能的话,检索应用的x和y值并将它们放入适当的注释中会很复杂。最好的选择似乎是使用numpy.histogram进行合并,并使用go.Bar设置图形。下面的代码段将产生以下图:

enter image description here

完整代码:

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

今天早晨,我在尝试绘制TDD百分比的直方图时遇到了同样的问题。使用plotly,我想进行归一化(histnorm:“ percent”),以便可以查看每月TDD值的百分比而不是计数。我通过简单地执行 print(tdd_hist)

找到了该解决方案

首先,我将直方图打印到控制台上,并看到此输出...

Figure({
'data': [{'alignmentgroup': 'True','bingroup': 'x','histnorm': 'percent','hovertemplate': 'Total Demand Distortion TDD %=%{x}<br>count=%{y}<extra></extra>','legendgroup': '','marker': {'color': '#636efa'},'name': '','offsetgroup': '','orientation': 'v','showlegend': False,'type': 'histogram','x': array([0.67,0.68,...,2.41,2.48,2.01]),'xaxis': 'x','yaxis': 'y'}],'layout': {'barmode': 'relative','legend': {'tracegroupgap': 0},'template': '...','title': {'text': 'Percent Histogram of TDD%'},'xaxis': {'anchor': 'y','domain': [0.0,1.0],'title': {'text': 'Total Demand Distortion TDD %'}},'yaxis': {'anchor': 'x','title': {'text': 'count'},'type': 'log'}}

现在我可以清楚地看到要更改此设置,我要做一个

tdd_hist.layout.yaxis.title.text = 'Percent'

它有效!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...