4

我有类似于此的数据框:

>>>Hour    Level   value   
0  7        H      1.435
1  7        M      3.124
2  7        L      5.578
3  8        H      0.435
4  8        M      2.124
5  8        L      4.578

我想在情节中创建折线图,该折线图将基于“级别”列具有不同的线条样式。

现在我有默认线型的折线图:

import plotly.graph_objects as go
fig = px.line(group, x="Hour", y="value",color='level', title='Graph',category_orders={'level':['H','M','L']}
             ,color_discrete_map={'H':'royalblue','M':'orange','L':'firebrick'})

fig.show()

在此处输入图像描述

我想控制每个级别的线型。直到知道我看到这样做的唯一方法是为每个“级别”添加,但使用 add_trace 如下:

# Create and style traces
fig.add_trace(go.Scatter(x="Hour", y="value", name='H',
                         line=dict(dash='dash')))
fig.add_trace(go.Scatter(x="Hour", y="value", name = 'M',
                         line=dict(dash='dot')))
fig.show()

但我不断收到此错误:

ValueError:为分散的“x”属性接收到的“builtins.str”类型的无效值接收到的值:“小时”

The 'x' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series

我的最终目标是控制图表中线条的线条样式,如果我能在“px.line”部分中做到这一点会更好

4

1 回答 1

5

您可以通过数据框中的变量设置不同样式的一种方法是:

line_dash='Level'

阴谋

在此处输入图像描述

完整代码

import plotly.graph_objects as go
import pandas as pd
import numpy as np
import plotly.io as pio
import plotly.express as px


group = pd.DataFrame({'Hour': {0: 7, 1: 7, 2: 7, 3: 8, 4: 8, 5: 8},
 'Level': {0: 'H', 1: 'M', 2: 'L', 3: 'H', 4: 'M', 5: 'L'},
 'value': {0: 1.435,
  1: 3.1239999999999997,
  2: 5.577999999999999,
  3: 0.435,
  4: 2.124,
  5: 4.578}})

import plotly.graph_objects as go
fig = px.line(group, x="Hour", y="value",color='Level', title='Graph',category_orders={'Level':['H','M','L']}
             ,color_discrete_map={'H':'royalblue','M':'orange','L':'firebrick'}, line_dash='Level')

fig.show()
于 2020-10-26T11:01:34.393 回答