改变条形颜色

时间:2020-09-29 00:36:38

标签: python pandas plotly

这是我的代码。我之前已经做过,而且奏效了。我希望负极条为红色,正极条为绿色,但我只是变黄了。

import pandas as pd
import plotly.express as px

deciles = pd.read_csv('https://github.com/ngpsu22/2016-2018-ASEC-/raw/master/deciles.csv')

fig = px.bar(deciles, x="deciles", y="percent_change",
             text='percent_change',
             height=800,
            labels={
                     "percent_change": "Percent change",
                     "deciles": "Decile"
                 },
            color_discrete_map={'10th': '#6aaa96',
                                '20th': '#6aaa96',
                                '30th': '#6aaa96',
                                '40th': '#6aaa96',
                                '50th': '#6aaa96',
                                '60th': '#e67f83',
                                '70th': '#e67f83',
                                '80th': '#e67f83',
                               '90th': '#e67f83'})

fig.update_layout(
    title='Average percent change in real resources per person',
    xaxis_tickfont_size=14,
    yaxis=dict(
        title='Percent change in real resources',
        titlefont_size=16,
        tickfont_size=14))
fig.update_traces(textposition='outside')
fig.update_traces(texttemplate='%{text}%')
fig.update_layout(uniformtext_minsize=14, uniformtext_mode='hide', xaxis_tickfont_size=16)
fig.show()

1 个答案:

答案 0 :(得分:1)

您最好添加一个名为color的新列,并在plotly.expressimport plotly.graph_objects as go中使用

import pandas as pd
import plotly.express as px
import numpy as np

deciles = pd.read_csv('https://github.com/ngpsu22/2016-2018-ASEC-/raw/master/deciles.csv')

# here you define the color
deciles["color"] = np.where(deciles["percent_change"] >= 0, 'green', "red")

fig = px.bar(deciles, x="deciles", y="percent_change",
             text='percent_change',
             color='color',
             height=800,
             labels={"percent_change": "Percent change",
                     "deciles": "Decile"
                 },)\
        .update_traces(showlegend=False) # you don't need legend in this case

fig.update_layout(
    title='Average percent change in real resources per person',
    title_x=0.5, # title is nicer if centered
    xaxis_tickfont_size=14,
    yaxis=dict(
        title='Percent change in real resources',
        titlefont_size=16,
        tickfont_size=14))
fig.update_traces(textposition='outside')
fig.update_traces(texttemplate='%{text}%')
fig.update_layout(uniformtext_minsize=14, uniformtext_mode='hide', xaxis_tickfont_size=16)
fig.show()

enter image description here