【问题标题】:How to make different color bar for value above and below 0 for plotly chart如何为绘图图表的高于和低于 0 的值制作不同的颜色条
【发布时间】:2019-09-10 07:06:38
【问题描述】:

我已经通过 plotly 生成了一个条形图,我怎样才能使 0 以上的条形图为绿色,而 0 以下的条形图为红色?

import plotly
import plotly.graph_objs as go
plotly.offline.init_notebook_mode(connected=True)
trace1 = go.Bar(
    x=df.symbol,
    y=df["percentageChange30dBtc"],

    name='Top10',
    marker = dict(color = 'rgba(63, 195, 128, 1)', 
                              line = dict(color='rgb(0,0,0)',width=1.5)),
   text=df.percentageChange30dBtc,
        textposition='outside'
)
##rgba(252, 214, 112, 1),'rgba(255,174,255,0.5)'
data = [trace1]
plotly.offline.iplot({
    "data": data,
    "layout": go.Layout(barmode='group', yaxis=dict(tickformat=".0%"),title="24H Change Binance"  #tickformat=".0%"
     ,width=800,height=600,)
})

【问题讨论】:

    标签: python pandas plotly


    【解决方案1】:

    您可以在标记上传递颜色列表, (假设 df["percentageChange30dBtc"] 值是数字,如果字符串以% 结尾,则使用float(x.replace('%',''))>0 而不是x>0

    import plotly
    import plotly.graph_objs as go
    plotly.offline.init_notebook_mode(connected=True)
    trace1 = go.Bar(
        x=df.symbol,
        y=df["percentageChange30dBtc"],
    
        name='Top10',
        marker = dict(color = ['rgba(63, 195, 128, 1)' if x>0 else 'rgba(219, 10, 91, 1)' for x in df["percentageChange30dBtc"]], 
                     line = dict(color='rgb(0,0,0)',width=1.5)),
       text=df.percentageChange30dBtc,
            textposition='outside'
    )
    ##rgba(252, 214, 112, 1),'rgba(255,174,255,0.5)'
    data = [trace1]
    plotly.offline.iplot({
        "data": data,
        "layout": go.Layout(barmode='group', yaxis=dict(tickformat=".0%"),title="24H Change Binance"  #tickformat=".0%"
         ,width=800,height=600,)
    })
    

    【讨论】:

    • 谢谢。我正要试一试。
    • 但它的输出是“文件””,第 6 行 marker = dict(color = 'rgba(63, 195, 128, 1)' if x >0 else 'rgba(219, 10, 91, 1)' for x in top_10["sep_return"], ^ SyntaxError: invalid syntax"
    • color 应该是一个列表,color = ['rgba(63, 195, 128, 1)' if x >0 else 'rgba(219, 10, 91, 1)' for x in top_10["sep_return"]]
    猜你喜欢
    • 1970-01-01
    • 2021-09-10
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多