在基于列的折线图中添加参考线
Posted
技术标签:
【中文标题】在基于列的折线图中添加参考线【英文标题】:adding reference line in line chart based on a column 【发布时间】:2021-08-07 07:57:51 【问题描述】:我有一个这样的数据框样本
我想绘制一个折线图,x 轴为索引,y 轴为振幅,我正在使用
我有一个折线图,但如何添加参考线以显示地震发生在我期待这样或类似图表的点
【问题讨论】:
【参考方案1】:如果您使用的是 4.12.0 的 plotly > 版本,则可以使用 plotly.express 的“add_vline”: https://plotly.com/python/horizontal-vertical-shapes/
import plotly.express as px
data="date":["2007-10-02 00:00:00","2007-10-02 00:00:20","2007-10-02 00:00:40","2007-10-02 00:01:00"],
"ampli":[35,39.37,39.48,36],"quake":[np.nan,np.nan,4.3,np.nan]
df=pd.DataFrame(data)
df['date']=pd.to_datetime(df['date'],format="%Y/%m/%d %H:%M:%S")
df.set_index("date",inplace=True)
df_quake = df[df['quake'].notna()]
fig2=px.line(df,x=df.index, y="ampli",title="ampli")
fig2.add_vline(x=df_quake.index, line_width=3, line_dash="dash", line_color="green")
plotly.offline.plot(fig2, filename='test2.html')
否则,你可以尝试用 graph_object 做一些事情:
import pandas as pd
import plotly.graph_objects as go
import plotly
import numpy as np
data="date":["2007-10-02 00:00:00","2007-10-02 00:00:20","2007-10-02 00:00:40","2007-10-02 00:01:00"],
"ampli":[35,39.37,39.48,36],"quake":[np.nan,np.nan,4.3,np.nan]
df=pd.DataFrame(data)
df['date']=pd.to_datetime(df['date'],format="%Y/%m/%d %H:%M:%S")
df.set_index("date",inplace=True)
df_quake = df[df['quake'].notna()]
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.index, y=df["ampli"],
mode='lines',
name='lines'))
fig.add_trace(go.Scatter(x=df_quake.index, y=df_quake["ampli"],
mode='markers',
name='quake',
marker='size':10))
plotly.offline.plot(fig, filename='test.html')
结果:
【讨论】:
以上是关于在基于列的折线图中添加参考线的主要内容,如果未能解决你的问题,请参考以下文章