我正在尝试将线型映射到具有多个子图的pandas
图中plotly
数据框中的分类数据列。
我有一个数据框df
等效于:
from datetime import datetime
import numpy as np
df = pd.DataFrame({'date':pd.date_range(start='01/01/2020',periods=100),
'y_one':np.linspace(1,100,100),
'y_two':np.linspace(100,1,100)})
df['today'] = df.date.apply(lambda date: 'the_future' if date > datetime.today() else 'the_past')
我需要在
y_one
上绘制多条线(y_two
,date_range
)。我想将线条固定为过去,并将虚线划线为将来,即将线型映射到df['today']
。到目前为止,我已经实现的绘图代码是:
import plotly.graph_objects as go
from plotly.offline import plot
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=df["date"],
y=df["y_one"],
mode="lines",
line=dict(color='black',
)
)
)
fig.add_trace(
go.Scatter(
x=df["date"],
y=df["y_two"],
mode="lines",
line=dict(color='red'),
)
)
plot(fig)
有没有办法在具有多个子图的
plotly
中实现此用例? 最佳答案
可能不是最优雅的解决方案,但是如果要绘制的列很多,则可以最终使用循环,可以考虑使用循环。
import plotly.graph_objects as go
import pandas as pd
import numpy as np
df = pd.DataFrame({'date':pd.date_range(start='01/01/2020',periods=100),
'y_one':np.linspace(1,100,100),
'y_two':np.linspace(100,1,100)})
df["is_future"] = df["date"]>pd.datetime.today()
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=df[df["is_future"]==False]["date"],
y=df[df["is_future"]==False]["y_one"],
mode="lines",
legendgroup="y_one",
name = "y_one",
line=dict(color='black',)))
fig.add_trace(
go.Scatter(
x=df[df["is_future"]==True]["date"],
y=df[df["is_future"]==True]["y_one"],
mode="lines",
legendgroup="y_one",
name = "y_one",
showlegend=False,
line=dict(color='black',dash='dash')))
fig.add_trace(
go.Scatter(
x=df[df["is_future"]==False]["date"],
y=df[df["is_future"]==False]["y_two"],
mode="lines",
legendgroup="y_two",
name = "y_two",
line=dict(color='red'),))
fig.add_trace(
go.Scatter(
x=df[df["is_future"]==True]["date"],
y=df[df["is_future"]==True]["y_two"],
mode="lines",
legendgroup="y_two",
name = "y_two",
showlegend=False,
line=dict(color='red', dash='dash'),))
fig.show()
关于python - 在python中将线型映射到具有多个子图的绘图中的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59949512/