简体   繁体   中英

Can I add a vline and hline to a plotly plot ignoring marginal plots?

I am moving a visualization from the seaborn library to the plotly library. I want a scatterplot with marginal histograms for my x and y variables. I want to show a vertical and horizontal line for the average of my x and y variables.

To show my problem I created a dummy dataframe of random X and Y values

import pandas as pd
import numpy as np
import seaborn as sns
import plotly.express as px

df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('XY'))

I want to replicate the seaborn library output on plotly.

g = sns.JointGrid(data=df, x="X", y="Y")
g.plot(sns.scatterplot, sns.histplot)
g.refline(x=df.X.mean(), y=df.Y.mean())

plt.show()

海底情节

When I do something similar on plotly using add_line and add_hline I get the following:

df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('XY'))
fig = px.scatter(df, x='X', y='Y',
                marginal_y="histogram", marginal_x="histogram",
                width=800, height=600)
fig.add_hline(y=df['X'].mean(), line_dash='dash', annotation_text= f"{df['X'].mean():.0f}")
fig.add_vline(x=df['Y'].mean(), line_dash='dash', annotation_text=f"{df['Y'].mean():.0f}")

fig.show()

密谋

My issue is that the horizontal line is plotted also plotted on the marginal x plot and the vertical line is also plotted on the marginal y plot. Is there a way to prevent the horizontal line to be plotted on the marginal x plot and the vertical line to be plotted on the marginal y plot?

You can define row and column of the panel grid when plotting hline/vline:

fig.add_hline(y=df['X'].mean(), line_dash='dash', row=1, annotation_text= f"{df['X'].mean():.0f}")
fig.add_vline(x=df['Y'].mean(), line_dash='dash', col=1, annotation_text=f"{df['Y'].mean():.0f}")

Sample 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