【问题标题】:Plotly express update of the pie chartplotly express 更新饼图
【发布时间】:2023-03-19 06:40:02
【问题描述】:

下面的代码会生成一个以图片形式呈现的饼图。我需要在饼图中的价格后添加一个 $ 符号,有人可以帮我这样做吗?我刚刚开始探索 :) 提前谢谢你!

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

【问题讨论】:

    标签: python plotly data-science pie-chart plotly-express


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 1970-01-01
      • 2015-01-12
      • 2021-03-25
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2017-05-14
      相关资源
      最近更新 更多