我的数据框 df 如下所示。我需要更改什么,每次运行都有自己的线条(颜色),并且“Val_B”列中的值是虚线,“Val_A”是实线?
import pandas as pd
import plotly.express as px
df = pd.DataFrame(
{
"Run": (
1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6
),
"Point": (
1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,
),
"Val_A": (
78, 79, 77, 78, 79, 77, 78, 79, 77, 78, 79, 77, 78, 79, 77, 78, 79, 77,
),
"Val_B": (
76, 75, 74, 76, 75, 74, 76, 75, 74, 76, 75, 74, 76, 75, 74, 76, 75, 74,
),
}
)
# Create the line plot with solid line for Val_A and dashed line for Val_B
fig = px.line(df, x="Point", y=["Val_A", "Val_B"], color="Run",
title="Line Plot with Solid and Dashed Lines for Each Run")
# Show the plot
fig.show()
所以我最终应该得到一个图,有 12 条线、6 种颜色和两种线条样式。
由于express不允许详细设置,所以我使用了图形对象。按数据框中的行类别提取数据,并用数据绘制折线图。折线图目标有两种类型,因此我们指定两种类型。为每个指定不同的线型。将颜色指定为与循环计数器相同的颜色。此外,由于两种类型的图例是按原样枚举的,因此它们被分组在一起并用作每个值的图例。如果不需要分组,请禁用它。
import plotly.graph_objects as go
import plotly.express as px
colors = px.colors.qualitative.Plotly
fig = go.Figure()
for i,r in enumerate(df['Run'].unique()):
dff = df.query('Run == @r')
fig.add_trace(go.Scatter(
x=dff['Point'],
y=dff['Val_A'],
mode='lines',
name=str(r),
legendgroup='Val_A',
legendgrouptitle=dict(text='Val_A'),
line=dict(color=colors[i])))
fig.add_trace(go.Scatter(
x=dff['Point'],
y=dff['Val_B'],
mode='lines',
name=str(r),
legendgroup='Val_B',
legendgrouptitle=dict(text='Val_B'),
line=dict(color=colors[i],dash='dash')
))
fig.update_layout(height=500, xaxis_title='Point', yaxis_title='value')
fig.show()