使用plotly.express以“线+标记”模式绘制交互式图形

时间:2020-04-22 05:53:52

标签: python pandas numpy matplotlib plotly

df

                        id      timestamp               data    Date            Start   
timestamp                                   
2020-01-15 06:12:49.213 40250   2020-01-15 06:12:49.213 20.0    2020-01-15      NaN 
2020-01-15 06:12:49.313 40251   2020-01-15 06:12:49.313 19.5    2020-01-15      0.0 
2020-01-15 08:05:10.083 40256   2020-01-15 08:05:10.083 20.0    2020-01-15      1.0 
2020-01-15 08:05:10.183 40257   2020-01-15 08:05:10.183 20.5    2020-01-15      0.0 
2020-01-15 09:01:50.993 40310   2020-01-15 09:01:50.993 21.0    2020-01-15      0.0 
2020-01-15 09:01:51.093 40311   2020-01-15 09:01:51.093 21.5    2020-01-15      0.0 
2020-01-15 09:51:01.890 40336   2020-01-15 09:51:01.890 22.0    2020-01-15      0.0 

我想使用plotly.express绘制交互式图形,用Start(是虚拟变量)和mode='lines+markers'绘制颜色。但是我无法添加行。目前,使用下面的代码

import plotly.express as px

fig = px.line(df, x="timestamp", y="data", title='xxx')
fig = px.scatter(df, x="timestamp", y="data",color='Start')   
fig.show()

我获得了情节 enter image description here


更新:

尝试:

import plotly.express as px

fig = px.line(x=df['timestamp'], y=df['data'])
fig.add_scatter(x=df['timestamp'], y=df['data'], marker_color=df['Start'])
返回的

enter image description here

1 个答案:

答案 0 :(得分:1)

问题在于代码中的图形对象被覆盖,即散布图代替了线图,而不是被添加到线图。

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'timestamp': ['2020-01-15 06:12:49.213', '2020-01-15 06:12:49.313', '2020-01-15 08:05:10.083', '2020-01-15 08:05:10.183',
                                 '2020-01-15 09:01:50.993', '2020-01-15 09:01:51.093', '2020-01-15 09:51:01.890'],
                   'data': [20.0, 19.5, 20.0, 20.5, 21.0, 21.5, 22.0],
                   'start': [0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0]})


fig = px.line(x=df['timestamp'], y=df['data'])
fig.add_scatter(x=df['timestamp'], y=df['data'], mode='markers', marker_color=df['start'], marker_size=10)

fig.update_layout(plot_bgcolor='#bababa', showlegend=False)

fig.show()

enter image description here

相关问题