I have dataframe tha tlooks similar to this:
JavaScript
x
8
1
>>>Hour Level value
2
0 7 H 1.435
3
1 7 M 3.124
4
2 7 L 5.578
5
3 8 H 0.435
6
4 8 M 2.124
7
5 8 L 4.578
8
I want to create line chart in plotly that will have different line style based in the column “level”.
Right now I have the line chart with the deafult line style:
JavaScript
1
6
1
import plotly.graph_objects as go
2
fig = px.line(group, x="Hour", y="value",color='level', title='Graph',category_orders={'level':['H','M','L']}
3
,color_discrete_map={'H':'royalblue','M':'orange','L':'firebrick'})
4
5
fig.show()
6
I would like to control the linestyle for each level. until know I saw that the only way to do this is to add for each “level” but using add_trace as following:
JavaScript
1
7
1
# Create and style traces
2
fig.add_trace(go.Scatter(x="Hour", y="value", name='H',
3
line=dict(dash='dash')))
4
fig.add_trace(go.Scatter(x="Hour", y="value", name = 'M',
5
line=dict(dash='dot')))
6
fig.show()
7
but I keep getting this error:
ValueError: Invalid value of type ‘builtins.str’ received for the ‘x’ property of scatter Received value: ‘Hour’
JavaScript131The 'x' property is an array that may be specified as a tuple,
2list, numpy array, or pandas Series
3
My end goal is to control the linestyle of the lines in my charts, better if I can do thatinside the part of “px.line”
Advertisement
Answer
One way you can set different styles through variables in your dataframe is:
JavaScript
1
2
1
line_dash='Level'
2
Plot
Complete code
JavaScript
1
22
22
1
import plotly.graph_objects as go
2
import pandas as pd
3
import numpy as np
4
import plotly.io as pio
5
import plotly.express as px
6
7
8
group = pd.DataFrame({'Hour': {0: 7, 1: 7, 2: 7, 3: 8, 4: 8, 5: 8},
9
'Level': {0: 'H', 1: 'M', 2: 'L', 3: 'H', 4: 'M', 5: 'L'},
10
'value': {0: 1.435,
11
1: 3.1239999999999997,
12
2: 5.577999999999999,
13
3: 0.435,
14
4: 2.124,
15
5: 4.578}})
16
17
import plotly.graph_objects as go
18
fig = px.line(group, x="Hour", y="value",color='Level', title='Graph',category_orders={'Level':['H','M','L']}
19
,color_discrete_map={'H':'royalblue','M':'orange','L':'firebrick'}, line_dash='Level')
20
21
fig.show()
22