猿问

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

有没有办法在 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")

https://img3.mukewang.com/64db59330001b02b09300538.jpg

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

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


杨__羊羊
浏览 202回答 3
3回答

阿晨1998

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

白板的微信

据我所知,绘图直方图没有文本属性。事实证明,如果可能的话,检索应用的 x 和 y 值并将它们放入适当的注释中也是很复杂的。您最好的选择似乎是使用numpy.histogram处理分箱并使用go.Bar. 下面的代码片段将产生以下图:完整代码:import numpy as npimport plotly.express as pximport plotly.graph_objects as go# sample datadf = px.data.tips()# create binsbins = [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 = countsfig.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()

MM们

今天早上我在尝试绘制 TDD 百分比直方图时遇到了同样的问题。我想使用plotly 进行标准化(histnorm:“百分比”),这样我就可以看到每月 TDD 值的百分比而不是计数。我通过简单地执行print(tdd_hist)找到了这个解决方案首先,我将直方图打印到控制台并看到这个输出......Figure({'data': [{'alignmentgroup': 'True',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'bingroup': 'x',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'histnorm': 'percent',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'hovertemplate': 'Total Demand Distortion TDD %=%{x}<br>count=%{y}<extra></extra>',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'legendgroup': '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'marker': {'color': '#636efa'},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'name': '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'offsetgroup': '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'orientation': 'v',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'showlegend': False,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'type': 'histogram',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'x': array([0.67, 0.68, 0.68, ..., 2.41, 2.48, 2.01]),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'xaxis': 'x',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'yaxis': 'y'}],'layout': {'barmode': 'relative',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'legend': {'tracegroupgap': 0},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'template': '...',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'title': {'text': 'Percent Histogram of TDD%'},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'Total Demand Distortion TDD %'}},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'count'}, 'type': 'log'}}现在我可以清楚地看到,为了改变这一点,我做了一个tdd_hist.layout.yaxis.title.text = 'Percent'
随时随地看视频慕课网APP

相关分类

Python
我要回答