当使用plotly express进行绘制时,我已经能够轻松地将列用作颜色变量,但是很难用plotly.graph_objects.Scatter来做同样的事情。而且,所有线路都已连接,如何将它们分开?
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import pandas as pd
x_values = range(1, 11)
y_values = ['a', 'b', 'c']
xs, ys, zs = [], [], []
for y in y_values:
for x in x_values:
#print(x, y)
xs.append(x)
ys.append(y)
zs.append(np.random.rand())
d = pd.DataFrame({'x': xs, 'y': ys, 'z': zs})
px.line(d, x='x', y='z', color='y')
fig = go.Figure(data=go.Scatter(
x=d['x'],
y=d['y'],
mode='lines'
))
fig.show()
编辑:我知道我们可以在行中使用不同的迹线,但是我真的想复制Plotly Express可以执行的操作。
这里您应该将df
从长到宽转换,例如以pd.pivot_table
为例,并为所需的每一列添加一个迹线。
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import pandas as pd
x_values = list(range(1, 11))
y_values = ['a', 'b', 'c']
df = pd.DataFrame({"x":x_values*len(y_values),
"y":np.repeat(y_values,len(x_values)),
"z":np.random.rand(len(x_values)*len(y_values))})
# px.line(df, x='x', y='z', color='y')
# long 2 wide
pv = pd.pivot_table(df,
index = "x",
columns="y",
values = "z")\
.reset_index()
fig = go.Figure()
for col in pv.columns[1:]:
fig.add_trace(go.Scatter(
x=pv['x'],
y=pv[col],
mode='lines',
name=col
))
fig.show()