gpt4 book ai didi

python - 条件颜色样式 : plotly go. Bar

转载 作者:行者123 更新时间:2023-12-04 00:15:58 26 4
gpt4 key购买 nike

我想将条件样式添加到 plotly 堆叠的条形图中。具体来说,堆栈的顶部栏将是基于 x 轴值的条件。

这是我的代码:

# sample df
df = pd.DataFrame({'Date': ['2010 - Q3','2010 - Q4','2011 - Q1','2011 - Q2','2011 - Q3','2011 - Q4'],
'Rate' : ['11.4','12.2','14.4','15.5','10.1','13.1'],
'Rate1': ['2.1','2.3','1.9','1.6','2.5','1.1']
})


clrs = 'rgb(222,0,0)'


fig = go.Figure(

data=[

go.Bar(
x=df['Date'],
y=df['Rate'],
name='Natural Level'
),

go.Bar(
x=df['Date'],
y=df['Rate1']),
name='Change',
marker=dict(color=clrs)
)

],

layout=go.Layout(

title='Measuring excess demand and supply in the market.',

xaxis=dict(
tickangle=90,
tickfont=dict(family='Rockwell', color='crimson', size=14)
),

yaxis=dict(
title='Rate',
showticklabels=True
),

barmode='stack',

)
)

clrs 变量以 x 轴值列表为条件获取颜色值。即 clrs = rgb(222,0,0) if df['Date'] in lst else rgb(0,222,0).

其中 lst 是 x 轴值的列表。

enter image description here

最佳答案

原始方法:你可以根据你的条件在你的df中创建一个Color列,然后将该列传递给marker=dict( color=clrs).

编辑:您可以根据 Date 列是否在 lst 中对数据框进行切片,然后分别添加数据框的两个部分使用跟踪,指定每个跟踪的颜色。这不是最漂亮的解决方案,如果你有两种以上的颜色,应该用循环替换,但希望能在这里完成工作。

import pandas as pd
import plotly.graph_objects as go

## sample df
df = pd.DataFrame({'Date': ['2010 - Q3','2010 - Q4','2011 - Q1','2011 - Q2','2011 - Q3','2011 - Q4'],
'Rate' : ['11.4','12.2','14.4','15.5','10.1','13.1'],
'Rate1': ['2.1','2.3','1.9','1.6','2.5','1.1']
})

## first and last bar are in lst
lst = ['2010 - Q3', '2011 - Q4']

## NOT NEEDED ##

## add a color column to the df, apply along row
## df['Color'] = df.apply(lambda x: 'rgb(222,0,0)' if x['Date'] in lst else 'rgb(0,222,0)', axis=1)
## clrs = 'rgb(222,0,0)'

fig = go.Figure(

data=[

go.Bar(
x=df['Date'],
y=df['Rate'],
name='Natural Level'
),

],

layout=go.Layout(

title='Measuring excess demand and supply in the market.',

xaxis=dict(
tickangle=90,
tickfont=dict(family='Rockwell', color='crimson', size=14)
),

yaxis=dict(
title='Rate',
showticklabels=True
),

barmode='stack',

)
)

## part of the dataframe in the lst
fig.add_trace(go.Bar(
x=df[df['Date'].isin(lst)]['Date'],
y=df[df['Date'].isin(lst)]['Rate1'],
name='Change1',
marker=dict(color='rgb(222,0,0)')
)

)
fig.add_trace(go.Bar(
x=df[~df['Date'].isin(lst)]['Date'],
y=df[~df['Date'].isin(lst)]['Rate1'],
name='Change2',
marker=dict(color='rgb(0,222,0)')
)

)

fig.show()

enter image description here

关于python - 条件颜色样式 : plotly go. Bar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63750767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com