【问题标题】:plotly: descending order in grouped bar chartplotly:分组条形图中的降序
【发布时间】:2021-11-05 09:52:57
【问题描述】:

我正在尝试

  1. 创建一个漂亮的图,按 LABEL 排序,然后按每个 LABEL 内的值排序。
  2. 如果可能,请删除图表底部的标签,因为我在图例中有说明。

图书馆:

from plotly import graph_objs as go
import plotly.express as px
import pandas as pd

我的数据如下所示:

df = pd.DataFrame({'LABEL': ['1', '1', '2', '2', '3', '3', '3', '3'],
                 'Cat2': ['a',  'b',  'a', 'b', 'c', 'a', 'e', 'f'],
                 'Value': [3, 2, 1, 4, 1, 3, 4, 1]})
df.sort_values(by=['LABEL', 'Value'], ascending=[True, False],inplace=True)

这是我的尝试:

COLOR_MAP = {str(i): c for i, c in enumerate(px.colors.qualitative.Light24)}

fig = go.Figure()

for i in df['LABEL'].unique():
    df_ = df[df['LABEL'] == i]
    fig.add_trace(go.Bar(
        x=[df_['LABEL'], df_['Cat2']],
        y=df_['Value'],
        marker=dict(color=COLOR_MAP[i]),
        name=f'{i}'))

fig.update_layout(legend_title='Cat1')

fig.update_layout(
    xaxis=dict(tickangle=45))

fig.update_layout(xaxis={'categoryorder': 'trace'}) # I tried: 'total descending', 'category descending', 'array'

结果:

我的期望:

提前致谢!!

【问题讨论】:

    标签: python-3.x plotly


    【解决方案1】:
    • plotly express 中要简单得多
    • 在定义 x 的数据框中定义一个新列
    from plotly import graph_objs as go
    import plotly.express as px
    import pandas as pd
    
    df = pd.DataFrame(
        {
            "LABEL": ["1", "1", "2", "2", "3", "3", "3", "3"],
            "Cat2": ["a", "b", "a", "b", "c", "a", "e", "f"],
            "Value": [3, 2, 1, 4, 1, 3, 4, 1],
        }
    )
    df.sort_values(by=["LABEL", "Value"], ascending=[True, False], inplace=True)
    
    # define a concatenated column for x
    df = df.assign(labx=df["LABEL"] + df["Cat2"])
    px.bar(
        df,
        x="labx",
        y="Value",
        hover_data=["Cat2"],
        color="LABEL",
        color_discrete_sequence=px.colors.qualitative.Light24,
    ).update_layout(
        xaxis={"tickmode": "array", "tickvals": df["labx"], "ticktext": df["Cat2"]}
    )
    

    【讨论】:

    • 谢谢。太棒了。我知道 plotly express 但没有想到那些选项:xaxis={"tickmode": "array", "tickvals": df["labx"], "ticktext": df["Cat2"]},它们对于实现这一结果最重要。
    猜你喜欢
    • 2017-01-04
    • 2021-01-18
    • 2020-02-28
    • 2023-02-26
    • 2021-02-14
    • 2021-01-17
    • 1970-01-01
    • 2015-05-16
    • 2018-12-07
    相关资源
    最近更新 更多