如何在Plotly图表图例中插入数值信息
Add Associated Values to Plotly Legend Labels
No worries, this is a common tweak that's straightforward once you know how to approach it. Since your UCL (and likely other control lines) are probably fixed values in your control chart, you just need to grab that value and concatenate it directly into the name parameter of your trace.
Here's how to adjust your code:
- First, extract the specific value you want to display for UCL. If your UCL column has the same value across all rows (typical for control charts), you can grab the unique value:
# Get the fixed UCL value from your DataFrame ucl_value = df_mean_control_chart['UCL'].unique()[0]
If you need a different value (like the last entry in the column), use this instead:
ucl_value = df_mean_control_chart['UCL'].iloc[-1]
- Update your trace's
nameto include the value. You can use an f-string for clean concatenation, and even format the number for readability:
fig.add_trace(go.Scatter( x=df_mean_control_chart['Samples'], y=df_mean_control_chart['UCL'], mode='lines', name=f'UCL - {ucl_value:.2f}', # Format to 2 decimal places, adjust as needed line=dict(color='black', width=2) ))
Bonus Tip
For other lines like ICL or LCL, repeat the same pattern: grab their respective values from your DataFrame and build the legend label the same way. For example:
icl_value = df_mean_control_chart['ICL'].unique()[0] fig.add_trace(go.Scatter( x=df_mean_control_chart['Samples'], y=df_mean_control_chart['ICL'], mode='lines', name=f'ICL - {icl_value:.2f}', line=dict(color='blue', width=2) ))
This will give you the exact legend labels you want: UCL - 100, ICL - 50, etc.
内容的提问来源于stack exchange,提问作者Felipe Roque
相关产品推荐
相关产品推荐

