将数据添加到记录道中,并使用suplots为短划线中的每个子图进行数据拆分

2024-10-02 00:23:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个虚拟数据帧:

import pandas as pd
df=pd.DataFrame({'A':[1,2,3,20,30,40],'B':['Tita','Tita','Tita','Burru','Burru','Burru'],'Z':[1,2,3,1,2,3]})

我想为B列中的每个值(Tita和Burru)提供一个子图

此代码生成预期输出:

from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=1, cols=2)
lista_syst=df.B.unique()

fig.add_trace(
    go.Scatter(x=df.loc[df['B'] == 'Tita', 'A'], y=df.loc[df['B'] == 'Tita', 'Z']),
    row=1, col=1
)

fig.add_trace(
    go.Scatter(x=df.loc[df['B'] == 'Burru', 'A'], y=df.loc[df['B'] == 'Burru', 'Z']),
    row=1, col=2
)

fig.update_layout(height=600, width=800, title_text="Subplots")
fig.show()

enter image description here

但是我想对B列中的n可能值进行自动设置,如下所示:

from plotly.subplots import make_subplots
import plotly.graph_objects as go
df=pd.DataFrame({'A':[1,2,3,20,30,40],'B':['Tita','Tita','Tita','Burru','Burru','Burru'],'Z':[1,2,3,1,2,3]})
fig = make_subplots(rows=1, cols=2)
lista_syst=df.B.unique()
for sist in lista_syst:
    print(sist)
    print(df.loc[df['B'] == sist, 'A'])
    for i in range(1,3):
        fig.add_trace(
            go.Scatter(y=df.loc[df['B'] == sist, 'A'],x=df.loc[df['B'] == sist, 'Z']),
            row=1,col=i

        )

最后一段代码,返回两个包含所有值的重复图(对于B中的两个值,同一个图两次),如何

enter image description here

能做我想做的吗


Tags: importgodfmakeasfigplotlyloc
1条回答
网友
1楼 · 发布于 2024-10-02 00:23:58

你在找这样的东西吗

from plotly.subplots import make_subplots
import plotly.graph_objects as go
df=pd.DataFrame({'A':[1,2,3,20,30,40],'B':['Tita','Tita','Tita','Burru','Burru','Burru'],'Z':[1,2,3,1,2,3]})

fig = make_subplots(rows=1, cols=2)
lista_syst=df.B.unique()

for sist in lista_syst:
    print(sist)
    print(df.loc[df['B'] == sist, 'A'])
    fig.add_trace(
            go.Scatter(
                x=df.loc[df['B'] == sist, 'Z'],
                y=df.loc[df['B'] == sist, 'A']))
fig.update_layout(height=600, width=800, title_text="Subplots")
fig.show()

这将为您提供: enter image description here

评论后编辑:
如果希望每个图形相邻,则可以执行以下操作:

from plotly.subplots import make_subplots
import plotly.graph_objects as go
df=pd.DataFrame({'A':[1,2,3,20,30,40],'B':['Tita','Tita','Tita','Burru','Burru','Burru'],'Z':[1,2,3,1,2,3]})
fig = make_subplots(rows=1, cols=2)
lista_syst=df.B.unique()
i=0
for sist in lista_syst:
    i=i+1
    fig.add_trace(
            go.Scatter(x=df.loc[df['B'] == sist, 'A'],y=df.loc[df['B'] == sist, 'Z']),
            row=1,col=i
        )
fig.update_layout(height=600, width=800, title_text="Subplots")
fig.show()

这将为您提供: enter image description here

相关问题 更多 >

    热门问题