我可以向堆积条形图添加颜色渐变吗?

问题描述 投票:0回答:1

我有一个 px 堆叠条形图,其中包含 x 轴上的 20 个期刊标题,以及每个期刊内的访问类型细分为堆叠段。访问类型数据跨多年。是否可以按颜色对访问类型和年份进行编码?如果可能的话,我想添加颜色代码的渐变来代表年份。

MWE

import pandas as pd
import plotly.express as px

d = {'Journal': ['Journal One', 'Journal One', 'Journal One', 'Journal One', 'Journal One', 'Journal One', 'Journal One'],
     'Access': ['Green', 'Green', 'Closed', 'Green', 'Closed', 'Green', 'Closed'],
     'Year': [2020, 2021, 2021, 2022, 2022, 2023, 2023],
     'Count': [1, 1, 5, 6, 3, 2, 4]}
df = pd.DataFrame(data=d)

fig = px.bar(df, x='Journal', y='Count', color='Access', text_auto=True,
            category_orders={'Access': ["Closed", "Green"]},
            color_discrete_map={
                "Closed": "#AB63FA",
                "Green": "#2CA02C"},
           title = f'Journal Titles by Access status and Year' )

fig.show()

dataframe

Stacked bar chart with multiple green and purple segments

我是否能够按年份指定绿色和紫色的渐变或透明度级别,以帮助区分色块内的不同数据?是否可以添加两种颜色编码?或者有更好的方式来展示这一切吗?

python plotly
1个回答
0
投票

我相信plotly.express 中只有一种统一的透明度设置。可以按图形对象中的属性进行提取,然后在循环过程中按年份进一步绘制图形。设置透明度,然后在循环过程中减去透明度。请将其修改为您想要的内容。另外,我正在将重复的图例项目制作成单个项目。

import plotly.graph_objects as go

fig = go.Figure()

for a in df['Access'].unique():
    dfa = df.query('Access == @a')
    opacity = 1.0
    colors = '#2CA02C' if a == 'Green' else '#AB63FA'
    for y in dfa['Year'].unique():
        dff = dfa.query('Year == @y')
        opacity -= 0.1
        fig.add_trace(go.Bar(
            x=dff['Journal'],
            y=dff['Count'],
            marker=dict(color=colors, opacity=opacity),
            name=a,
            text=dff['Count'],
            legendgroup=a,
        ))

# Make duplicate legend items unique
names = set()
fig.for_each_trace(
    lambda trace:
        trace.update(showlegend=False)
        if (trace.name in names) else names.add(trace.name))

fig.update_layout(legend_title_text='Access', height=500, barmode='stack')

fig.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.