情节:带有下拉菜单和离散标记颜色的散点图上的彩色传奇

发布于 2025-01-25 20:34:35 字数 4450 浏览 2 评论 0原文

长篇文章 - 我是Python和Plotly的新手,所以感谢您的帮助!

我正在使用带有自行车/锻炼数据的数据构建散点图,这些数据来自带有摘要指标(输出/工作,阻力,节奏/速度等)以及每个乘车的长度/持续时间。我正在尝试在散点图中构建两个功能:1)一个下拉菜单,用于更改/切换4个指标字段之间Y轴显示的数据(总输出,平均输出,平均节奏和平均电阻)和2)代表映射到离散颜色的数据值的传说,在这种情况下,ride.duration(每个记录/骑行都是5、10、20、20、30、45或60分钟)而且没有能力让他们两个同时做我想做的事情。

我已经能够通过动态的Y轴下拉列表构建一个散点图,并根据乘车持续时间为点上点,但是我无法显示乘车持续时间的传奇以表明持续时间映射的颜色。

我的代码如下:


#test dataset - this is just a couple of points, so it won't look like the screenshots I've provided but should hopefully do the job!
all_rides_clean = pd.DataFrame(np.array([['a2662', '2022-04-24 18:09:25', 145,120,78,42,20,"Ben"], 
                                        ['b10e', '2022-03-21 11:28:20', 128,71,66,35,30,"Emma"], 
                                        ['850g', '2021-01-19 11:29:31',121,101,80,38,45,"Leanne"],
                                        ['897b','2021-09-21 22:46:30',175,65,54,37,60,"Emma"]]),
                            columns=['id','created_at','Total Output','Avg Output','Avg Cadence','Average Resistance','ride.duration',
                                    'instructor.name'])
all_ride[['Total Output','Avg Output','Avg Cadence','Avg Resistance']] = all_ride[['Total Output','Avg Output','Avg Cadence','Avg Resistance']].apply(pd.to_numeric)

fig = go.Figure()

# dynamic y-axis dropdown labels
metrics = ['Total Output','Avg Output','Avg Cadence','Avg Resistance']

# make list of default plotly colors in hex
plotly_colors=[
                '#1f77b4',  # muted blue
                '#ff7f0e',  # safety orange
                '#2ca02c',  # cooked asparagus green
                '#d62728',  # brick red
                '#9467bd',  # muted purple
                '#8c564b',  # chestnut brown
                '#e377c2',  # raspberry yogurt pink
                '#7f7f7f',  # middle gray
                '#bcbd22',  # curry yellow-green
                '#17becf'   # blue-teal
              ]

# create dictionary to associate colors with unique categories
color_dict = dict(zip(all_rides_clean['ride.duration'].unique(),plotly_colors))

# map new column with hex colors to pass to go.Scatter()
all_rides_clean['hex']= all_rides_clean['ride.duration'].map(color_dict)

for column in metrics:
    fig.add_trace(
        go.Scatter(
            x = all_rides_clean['created_at'],
            y = all_rides_clean[column],
            name = column,
            mode = 'markers',
            #setting color legend
            marker=dict(color=all_rides_clean['hex']),
            showlegend=False
        )
    )
    
fig.update_layout(
    updatemenus=[go.layout.Updatemenu(
        active=0,
        buttons=list(
            [dict(label = 'Total Output',
                  method = 'update',
                  args = [{'visible': [True, False, False, False]}, # the index of True aligns with the indices of plot traces
                          {'title': 'Total Output',
                           'showlegend':False}]),
             dict(label = 'Avg Output',
                  method = 'update',
                  args = [{'visible': [False, True, False, False]},
                          {'title': 'Avg Output',
                           'showlegend':False}]),
             dict(label = 'Avg Cadence',
                  method = 'update',
                  args = [{'visible': [False, False, True, False]},
                          {'title': 'Avg Cadence',
                           'showlegend':False}]),
             dict(label = 'Avg Resistance',
                  method = 'update',
                  args = [{'visible': [False, False, False, True]},
                          {'title': 'Avg Resistance',
                           'showlegend':False}]),
            ])
        )
    ],
)
fig.show()

此代码产生以下图表:

“

,如您所见,Y轴可用y-axis toggle oktgle和散点点的颜色正确,但我似乎无法让颜色传奇显示出来以显示哪种颜色代表哪个行程持续时间。我已经尝试用showlegend弄乱,但这似乎只能控制每个跟踪的下拉传说(用于输出,电阻和节奏)。

当我使用plotly Express和硬码的锻炼指标值之一时,我已经能够显示出一个骑行持续时间的颜色传奇,就像这样:

fig = px.scatter(all_rides_clean, x='created_at', y='Total Output',color="ride.duration")

”

但这不是我想要的,因为我希望下拉 /能够动态更改不同输出,电阻和节奏之间y轴上显示的内容值。

任何人都知道如何使此颜色传说显示?

最终,我还想添加另一个下拉列表,以便能够动态更改彩色传奇中显示的离散数据(在乘车持续时间,乘车类型等之间),因此这里的任何提示都受到欢迎。

提前致谢!

Long post - I'm new to python and plotly, so appreciate the help!

I'm building a scatter plot with plotly using bike ride/workout data coming from a pandas dataframe with summary metrics (output/work, resistance, cadence/speed, etc.) as well as the length/duration for each ride. I'm trying to build in two features in particular into the scatter plot: 1) a dropdown menu to change/toggle the data displayed on the y-axis between 4 metrics fields (Total Output, Average Output, Average Cadence, and Average Resistance) and 2) a legend that represents data values mapped to discrete colors, in this case the ride.duration (each record/ride is either 5, 10, 20, 30, 45, or 60 min) and haven't been able to get both of them to do what I want at the same time.

I've been able to build a scatter plot with a dynamic y-axis dropdown and color the points according to the ride duration, but I can't get the ride duration legend to show up to indicate the color to duration mappings.

My code is below:


#test dataset - this is just a couple of points, so it won't look like the screenshots I've provided but should hopefully do the job!
all_rides_clean = pd.DataFrame(np.array([['a2662', '2022-04-24 18:09:25', 145,120,78,42,20,"Ben"], 
                                        ['b10e', '2022-03-21 11:28:20', 128,71,66,35,30,"Emma"], 
                                        ['850g', '2021-01-19 11:29:31',121,101,80,38,45,"Leanne"],
                                        ['897b','2021-09-21 22:46:30',175,65,54,37,60,"Emma"]]),
                            columns=['id','created_at','Total Output','Avg Output','Avg Cadence','Average Resistance','ride.duration',
                                    'instructor.name'])
all_ride[['Total Output','Avg Output','Avg Cadence','Avg Resistance']] = all_ride[['Total Output','Avg Output','Avg Cadence','Avg Resistance']].apply(pd.to_numeric)

fig = go.Figure()

# dynamic y-axis dropdown labels
metrics = ['Total Output','Avg Output','Avg Cadence','Avg Resistance']

# make list of default plotly colors in hex
plotly_colors=[
                '#1f77b4',  # muted blue
                '#ff7f0e',  # safety orange
                '#2ca02c',  # cooked asparagus green
                '#d62728',  # brick red
                '#9467bd',  # muted purple
                '#8c564b',  # chestnut brown
                '#e377c2',  # raspberry yogurt pink
                '#7f7f7f',  # middle gray
                '#bcbd22',  # curry yellow-green
                '#17becf'   # blue-teal
              ]

# create dictionary to associate colors with unique categories
color_dict = dict(zip(all_rides_clean['ride.duration'].unique(),plotly_colors))

# map new column with hex colors to pass to go.Scatter()
all_rides_clean['hex']= all_rides_clean['ride.duration'].map(color_dict)

for column in metrics:
    fig.add_trace(
        go.Scatter(
            x = all_rides_clean['created_at'],
            y = all_rides_clean[column],
            name = column,
            mode = 'markers',
            #setting color legend
            marker=dict(color=all_rides_clean['hex']),
            showlegend=False
        )
    )
    
fig.update_layout(
    updatemenus=[go.layout.Updatemenu(
        active=0,
        buttons=list(
            [dict(label = 'Total Output',
                  method = 'update',
                  args = [{'visible': [True, False, False, False]}, # the index of True aligns with the indices of plot traces
                          {'title': 'Total Output',
                           'showlegend':False}]),
             dict(label = 'Avg Output',
                  method = 'update',
                  args = [{'visible': [False, True, False, False]},
                          {'title': 'Avg Output',
                           'showlegend':False}]),
             dict(label = 'Avg Cadence',
                  method = 'update',
                  args = [{'visible': [False, False, True, False]},
                          {'title': 'Avg Cadence',
                           'showlegend':False}]),
             dict(label = 'Avg Resistance',
                  method = 'update',
                  args = [{'visible': [False, False, False, True]},
                          {'title': 'Avg Resistance',
                           'showlegend':False}]),
            ])
        )
    ],
)
fig.show()

This code produces the following chart:

here

And as you can see, the y-axis toggle works and the scatter points are colored correctly, but I can't seem to get the color legend to show up to show which colors represent which ride duration. I've tried messing around with showLegend, but that only seems to control the dropdown legend for each trace (for output, resistance, and cadence).

I've been able to get a ride duration color legend to display when I use plotly express and hard code one of the workout metrics values to the y-axis, like so:

fig = px.scatter(all_rides_clean, x='created_at', y='Total Output',color="ride.duration")

photo here

but that isn't what I'm looking for because I want the dropdown / ability to dynamically change what's displayed on the y-axis between the different output, resistance, and cadence values.

Anyone know how to get this color legend to display?

Ultimately, I would also like to add another dropdown to be able to dynamically change the discrete data displayed in the color legend (between ride duration, ride type, etc.), so any tips here welcomed.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文