gpt4 book ai didi

python - Plotly:如何为使用多条轨迹创建的图形设置调色板?

转载 作者:行者123 更新时间:2023-12-04 11:47:16 30 4
gpt4 key购买 nike

我使用下面的代码生成具有多个跟踪的图表。
然而,我知道为每个轨迹应用不同颜色的唯一方法是使用 randon 函数,该函数为颜色使用数字 RGB。
但随机颜色不利于演示。
我如何为下面的代码使用托盘颜色并且不会获得更多随机颜色?

groups53 = dfagingmedioporarea.groupby(by='Area')


data53 = []
colors53=get_colors(50)

for group53, dataframe53 in groups53:
dataframe53 = dataframe53.sort_values(by=['Aging_days'], ascending=False)
trace53 = go.Bar(x=dataframe53.Area.tolist(),
y=dataframe53.Aging_days.tolist(),
marker = dict(color=colors53[len(data53)]),
name=group53,
text=dataframe53.Aging_days.tolist(),
textposition='auto',


)


data53.append(trace53)

layout53 = go.Layout(xaxis={'title': 'Area', 'categoryorder': 'total descending', 'showgrid': False},

yaxis={'title': 'Dias', 'showgrid': False},
margin={'l': 40, 'b': 40, 't': 50, 'r': 50},
hovermode='closest',
template='plotly_white',


title={
'text': "Aging Médio (Dias)",
'y':.9,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top'})




figure53 = go.Figure(data=data53, layout=layout53)

最佳答案

已经提出并回答了许多关于 plotly 颜色主题的问题。
参见例如 Plotly: How to define colors in a figure using plotly.graph_objects and plotly.express?
但您似乎希望在不使用循环的情况下添加跟踪。
也许是因为跟踪的属性不仅在颜色上不同?据我所知,目前还没有关于如何有效地做到这一点的描述。

答案:

  • dir(px.colors.qualitative) 下找到许多可用的调色板, 或
  • 定义您自己的调色板,如 ['black', 'grey', 'red', 'blue'] , 和
  • 使用 next(palette) 一一检索对于您决定添加到图形中的每条轨迹。

  • next(palette)乍一看可能有点神秘,但使用 Python 很容易设置 itertools像这样:
    import plotly.express as px
    from itertools import cycle
    palette = cycle(px.colors.qualitative.Plotly)
    palette = cycle(px.colors.sequential.PuBu)
    现在您可以使用 next(palette)并在每次添加跟踪时返回颜色列表的下一个元素。最好的一点是,正如上面的代码所暗示的那样,颜色是循环返回的,因此当您使用所有颜色一次时,您永远不会到达列表的末尾,而是从头开始。
    示例图:
    enter image description here
    完整代码:
    import plotly.graph_objects as go
    import plotly.express as px
    from itertools import cycle

    # colors
    palette = cycle(px.colors.qualitative.Bold)
    #palette = cycle(['black', 'grey', 'red', 'blue'])
    palette = cycle(px.colors.sequential.PuBu

    # data
    df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")

    # plotly setup
    fig = go.Figure()

    # add traces
    country = 'Germany'
    fig.add_traces(go.Bar(x=[country],
    y = df[df['country']==country]['pop'],
    name = country,
    marker_color=next(palette)))

    country = 'France'
    fig.add_traces(go.Bar(x=[country],
    y = df[df['country']==country]['pop'],
    name = country,
    marker_color=next(palette)))

    country = 'United Kingdom'
    fig.add_traces(go.Bar(x=[country],
    y = df[df['country']==country]['pop'],
    name = country,
    marker_color=next(palette)))

    fig.show()

    关于python - Plotly:如何为使用多条轨迹创建的图形设置调色板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63604342/

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