简体   繁体   中英

Plotly make 2 subplots from different dataframes with shared legend

I have 2 dataframes (df1,df2), which have the same index . I want to:

  • make 2 subplots
  • subplot 1 has lines of df1 eg (px.line(df1))
  • subplot 2 has lines of df2 eg (px.line(df2))
  • Plot 1 and Plot 2 both share one legend (users) that on click selects both plots.

I have made code that generates the dfs and the plots, but am not sure how to put them togheter.

from pandas._libs.algos import diff_2d
import pandas as pd
import plotly.express as px


df1 = pd.DataFrame({
    'user1':[1,1,2,3,3,4,5,1,1,1,4,4,4,5,6,6,6,6,3],
    'user2':[3,4,5,5,5,2,1,3,4,4,4,5,6,6,4,3,6,6,3],
    'user3':[1,5,2,3,4,5,2,2,1,1,1,2,3,4,5,5,4,4,2],
              })

df2 = pd.DataFrame({
    'user1':[0,3,4,5,2,5,6,7,2,3,1,5,7,2,1,3,5,2,3],
    'user2':[3,3,4,5,6,7,2,1,3,1,3,5,6,7,2,2,2,3,9],
    'user3':[8,6,4,7,6,5,8,7,6,2,3,4,6,7,8,9,9,5,3],
              })

fig1 = px.line(df1)
fig1.update_layout(height=400, width=500, title_text="PLOT 1")
fig1.show()

fig2 = px.line(df2)
fig2.update_layout(height=400, width=500, title_text="PLOT 2 as subplot Plot 1, with shared legend")
fig2.show()

示例输出

It's simple if you concatenate the data frames adding a column that is the source data frame.

import pandas as pd
import plotly.express as px


df1 = pd.DataFrame(
    {
        "user1": [1, 1, 2, 3, 3, 4, 5, 1, 1, 1, 4, 4, 4, 5, 6, 6, 6, 6, 3],
        "user2": [3, 4, 5, 5, 5, 2, 1, 3, 4, 4, 4, 5, 6, 6, 4, 3, 6, 6, 3],
        "user3": [1, 5, 2, 3, 4, 5, 2, 2, 1, 1, 1, 2, 3, 4, 5, 5, 4, 4, 2],
    }
)

df2 = pd.DataFrame(
    {
        "user1": [0, 3, 4, 5, 2, 5, 6, 7, 2, 3, 1, 5, 7, 2, 1, 3, 5, 2, 3],
        "user2": [3, 3, 4, 5, 6, 7, 2, 1, 3, 1, 3, 5, 6, 7, 2, 2, 2, 3, 9],
        "user3": [8, 6, 4, 7, 6, 5, 8, 7, 6, 2, 3, 4, 6, 7, 8, 9, 9, 5, 3],
    }
)


px.line(
    pd.concat([d.assign(plot=n + 1) for n, d in enumerate([df1, df2])]),
    facet_row="plot",
)

output

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM