【问题标题】:Creating ONE stacked bar beside ONE normal bar in plotly?在情节中在一个普通条旁边创建一个堆叠条?
【发布时间】:2021-11-12 16:07:16
【问题描述】:

我有一个名为 'CountryCounts' 的系列,这是在我的原始数据框的“国家”列 OGdf['Country'] 上调用 .value_counts() 的结果。

United States           1234
United Kingdom           332
Canada                   111
France                    61
Australia                 55
                        ... 
Israel                     1
Bahamas                    1
Romania                    1
Greece                     1
United Arab Emirates       1
Name: Country, Length: 63, dtype: int64

我想要做的是创建一个情节条形图,其中第一行(在本例中为美国 - 1234)被绘制为自己的条形图。

然后每隔一行被绘制为一个堆积条(总长度将是其他行的总和),但每个单独的行都有悬停信息(这样你仍然可以看到英国作为它自己的颜色那个酒吧,加拿大等)

我创建了一个简短的函数来分离剩余的条目,直到它们与第一个相等:

def find_next_series_equivalent(series):
  primary = series[0]
  if series[1:-1].sum() > primary:
    i = 2
    while series[1:i].sum() < primary:
      i += 1
    return series[1:i]
  else:
    return series[1:-1]

我已经通过做直方图来尝试过:

fig = px.histogram(OGdf, x='Country', barmode='stack')

还有条形图:

first_entry = OGdf['Country'].value_counts()[0]
fig = px.bar(y = [first_entry.index], x= [first_entry.values], orientation='h')
fig.update_xaxes(title='# From Country')
fig.update_yaxes(title='Country')

othersdict = find_next_series_equivalent(OGdf['Country'].value_counts()).to_dict()
   

othersBar = go.Bar(
     y = othersdict.index,
     x = othersdict.values)

fig.add_trace(othersBar, row=1, col=1)

fig.update_layout(barmode='stack')

这两个都不能实现我的目标。非常感谢您的帮助。在此先感谢:)

(顺便说一句,我正在使用 plotly express 并且我的 pandas 绘图后端设置为 plotly)

【问题讨论】:

    标签: pandas plotly bar-chart plotly-python stacked-chart


    【解决方案1】:
    • 如果按照您的描述创建图形,这很简单。 xaxis 是两个值之一
    • rest 然后将参数设置为 plotly express bar
    • 有隐藏的图例,您可以根据需要显示,但可能会太长,超过 60 个国家/地区
    • 使用了来自value_counts() 的样本数据
    import plotly.express as px
    import io
    import pandas as pd
    import numpy as np
    
    df = pd.read_csv(io.StringIO("""United States           1234
    United Kingdom           332
    Canada                   111
    France                    61
    Australia                 55
    Israel                     1
    Bahamas                    1
    Romania                    1
    Greece                     1
    United Arab Emirates       1"""), sep="\s\s+", engine="python", header=None).rename(columns={0:"Country",1:"Count"})
    
    fig = px.bar(df, x=np.where(df["Country"].eq("United States"), "United States", "Other"), y="Count", 
           hover_data=["Country"], color="Country")
    
    # if legend is not wanted...
    fig = fig.update_layout(showlegend=False)
    fig
    

    【讨论】:

    • 非常感谢!我知道解决方案比我尝试做的要简单得多!非常感谢您的帮助!绝对的传奇
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2019-07-07
    • 2014-10-31
    • 1970-01-01
    相关资源
    最近更新 更多