【问题标题】:Horizontal stacked unique 100% bar chart plotly python水平堆叠的独特 100% 条形图 plotly python
【发布时间】:2021-10-08 05:50:36
【问题描述】:

我想用 plotly 绘制一个 100% 的水平条。

导入和数据如下。

import pandas as pd
from plotly.offline import plot
import plotly.graph_objects as go

df = pd.DataFrame([["Blue", 100 , 10.0],
                   ["Green", 30 , 3.0],
                   ["Red", 650, 65.0],
                   ["White", 65, 6.5],
                   ["Gray", 70, 7.0],
                   ["green", 50, 5.0],
                   ["white", 35 , 3.5]],
                  columns=["color", "total", "percentage"])

我想将所有颜色都放在一个条形图中(加到 100%),每种颜色都有不同的颜色并忽略大小写,将“绿色”和“绿色”计为一个“绿色”(5.0+3.0= 8.0),如下图所示:

但是当我尝试以下 (https://plotly.com/python/horizontal-bar-charts/ ) 时,我收到了一个错误:

import plotly
colors = plotly.colors.qualitative.D3

fig = go.Figure()
for i in range(0, len(df['total'][0])):
    for xd, yd in zip(df['total'], df['color']):
        fig.add_trace(go.Bar(
            x=[xd[i]], y=[yd],
            orientation='h',
            marker=dict(
                color=colors[i],
                line=dict(color='rgb(248, 248, 249)', width=1)
            )
        ))

还尝试了这种方法,每种颜色给我一个条:

fig = go.Figure()
fig.add_trace(go.Bar(
    y=df['color'],
    x=df['percentage'],
    name='Colors',
    orientation='h'
    )
)

fig.update_layout(barmode='stack')
fig.show()

我如何获得它?

【问题讨论】:

    标签: python pandas plotly bar-chart


    【解决方案1】:

    这不是普通的条形图。您需要根据百分比手动计算条形位置和宽度。

    # aggregate percentage by color, ignore case
    colors = df.groupby(df.color.str.lower()).percentage.sum()
    
    # reorder color index
    colors = colors.reindex(['blue', 'green', 'red', 'white', 'gray'])
    
    # calculate x bar positions
    x_barpos = colors.cumsum() - colors / 2
    
    # create figure
    fig = go.Figure(go.Bar(
        x=x_barpos, 
        y=[1] * len(colors), 
        width=colors, 
        marker_color=colors.index
    ))
    
    # set x axes labels
    fig = fig.update_xaxes(
        tickvals=list(range(0, 101, 25)), 
        ticktext=[str(x)+'%' for x in range(0, 101, 25)], 
        range=[0, 100])
    
    # remove y axes labels
    fig = fig.update_yaxes(showticklabels=False, range=[0, 1])
    
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2023-01-31
      • 2016-10-29
      • 2015-02-11
      • 2019-03-25
      相关资源
      最近更新 更多