python - plotly express 更新饼图
问题描述
下面的代码生成一个以图片显示的饼图。我需要在饼图中的价格后添加一个 $ 符号,有人可以帮我这样做吗?我刚开始探索 :) 提前谢谢你!
pie = data[["room_type","price"]]
pie_chart = pie.groupby(['room_type'], as_index=False).median()
fig3 = px.pie(pie_chart,
values='price',
names='room_type',
color_discrete_sequence =['#de425b','#ef805b','#f7b672'])
fig3.update_traces(hoverinfo='label+percent', textinfo='value', textfont_size=17)
fig3.update_layout(
title_text = 'Median of prices per room type',
legend_title = 'Room type',
title_font = dict(family='Courier', size=16, color='black'),
title_x=0.5,
font_family="Courier",
font_color="black",
legend_title_font_color="black"
)
解决方案
在 中fig.update_traces method
,您可以传递textinfo='text'
而不是textinfo='labels'
然后将文本定义为 DataFrame 中的价格列表,并以美元符号作为每个价格的前缀。
import pandas as pd
import plotly.express as px
# pie = data[["room_type","price"]]
# pie_chart = pie.groupby(['room_type'], as_index=False).median()
## recreate DataFrame
pie_chart = pd.DataFrame({
'room_type':['Entire room/apt','Private room','Shared room'],
'price': ['68','35','16']
})
fig3 = px.pie(pie_chart,
values='price',
names='room_type',
color_discrete_sequence =['#de425b','#ef805b','#f7b672'])
## pass a list of values
fig3.update_traces(
hoverinfo='label+percent',
text=['$' + price for price in pie_chart.price.values],
textinfo='text',
textfont_size=17)
fig3.update_layout(
title_text = 'Median of prices per room type',
legend_title = 'Room type',
title_font = dict(family='Courier', size=16, color='black'),
title_x=0.5,
font_family="Courier",
font_color="black",
legend_title_font_color="black"
)
fig3.show()
推荐阅读
- eclipse - Eclipse / PyDev 停止按钮不适用于 OSError:[WinError 6] 句柄无效错误
- sql - 即使查询不同,Postgres 也会缓存计划吗?
- html - Bootstrap中的联锁圆圈div问题
- python - 如何根据名称中的日期处理多个文件
- java - 为什么我的 Java 套接字接收的数组大小比发送的大?
- c# - 在 UWP C# 上选择时更改颜色
- c# - 尽管配置了 FK,但 EF Core 创建阴影属性
- python-3.x - 执行脚本Python时如何为参数添加名称
- numpy - 使用 numpy 2d 数组对齐 2 个句子中的单词
- flutter - 容器的孩子采取父母的形状