python - Plotly:如何使用 go.Bar 为组指定颜色?

标签 python plotly plotly-python

使用方法 plotly.graph_objs以与 plotly.express 类似的方式绘制 Pandas 数据- 专门为各种数据类型着色?

基于 Pandas 列中的值对数据类型进行分组的 plotly express 功能非常有用。不幸的是,我无法在我的系统中使用 express(因为我需要将图形对象发送到 orca )

我可以通过专门映射 Type 来获得相同的功能到颜色( full_plot 在下面的示例中),但是我有类型 A-Z,是否有更好的方法来映射每个可能的 Type在数据框中的颜色?

import pandas as pd
import plotly.express as px
import plotly.graph_objs as go

d = {'Scenario': [1, 2, 3, 1, 2,3],
     'Type': ["A", "A", "A", "B", "B", "B"],
     'VAL_1': [100, 200, 300, 400 , 500, 600],
     'VAL_2': [1000, 2000, 3000, 4000, 5000, 6000]}
df = pd.DataFrame(data=d)


def quick_plot(df):

    fig = px.bar(df, y='VAL_1',  x='Scenario',  color="Type", barmode='group')
    fig['layout'].update(title = "PX Plot",
                     width = 600, height = 400,
                     xaxis = dict(showgrid=False))
    fig.show()


def full_plot(df):

    colors = {'A': 'blue',
          'B': 'red'}
    s0=df.query('Type=="A"')
    s1=df.query('Type=="B"')

    fig = go.Figure()
    fig.add_trace(go.Bar(
        name='A',
         y=s0['VAL_1'],x=s0['Scenario'], marker={'color': colors['A']}))
    fig.add_trace(go.Bar(
        name='B',
         y=s1['VAL_1'],x=s1['Scenario'], marker={'color': colors['B']}))

    fig['layout'].update(title = "Full Plot",
                     width = 600, height = 400)

    fig.update_layout(barmode='group')
    fig.show()

quick_plot(df)
full_plot(df)

最佳答案

你可以简单地使用这样的字典:

colors = {'A':'steelblue',
          'B':'firebrick'}

唯一的挑战在于将每个唯一类型的数据帧分组,并使用 for 循环为每种类型添加新的跟踪。下面的代码片段负责生成此图:

enter image description here
# imports
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go

# data
d = {'Scenario': [1, 2, 3, 1, 2,3],
     'Type': ["A", "A", "A", "B", "B", "B"],
     'VAL_1': [100, 200, 300, 400 , 500, 600],
     'VAL_2': [1000, 2000, 3000, 4000, 5000, 6000]}
df = pd.DataFrame(data=d)

# assign colors to type using a dictionary
colors = {'A':'steelblue',
          'B':'firebrick'}

# plotly figure
fig=go.Figure()
for t in df['Type'].unique():
    dfp = df[df['Type']==t]
    fig.add_traces(go.Bar(x=dfp['Scenario'], y = dfp['VAL_1'], name=t,
                         marker_color=colors[t]))

fig.show()

关于python - Plotly:如何使用 go.Bar 为组指定颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61746001/

相关文章:

Python - 从文件中删除一行(使用条目的待办事项列表程序,与其他帖子不同)

python - django.apps : an error appears during the template rendering when I loop on get_models()

javascript - Plotly.js 中日期轴的最小缩放比例为一天

javascript - plotly PyQt : Get camera view properties

r - 绘图标记大小

python - Plotly:如何更改 3D 曲面图的配色方案?

Python 字符串比较不匹配从文件中读取的行

python - 在 dash 中,选择单选按钮时如何使用回调来更新图表?

python - Plotly-Dash:如何在 plotly dash 中为悬停功能编写交互式回调代码

python - 查找至少一行包含字母的列