简体   繁体   English

Seaborn/Plotly 多个 y 轴

[英]Seaborn/Plotly multiple y-axes

I would like to get a plot with more than two different y-axes in seaborn using a pandas dataframe similar to this example for matlotlib: https://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html I would like to get a plot with more than two different y-axes in seaborn using a pandas dataframe similar to this example for matlotlib: https://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

As it will be used in a function I want to be flexible in selecting how many and which column of a Pandas dataframe will be ploted.因为它将在 function 中使用,所以我想灵活地选择 Pandas dataframe 的列数和列。

Unfortunately Seaborn seems to only move the last added scale.不幸的是 Seaborn 似乎只移动了最后添加的比例。 Here is what I want to do with a Seaborn sample dataset:这是我想要对 Seaborn 示例数据集执行的操作:

import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import seaborn as sns

df=sns.load_dataset("mpg")
df=df.loc[df['model_year']<78]

show=['mpg','displacement','acceleration']

sns.set(rc={'figure.figsize':(11.7,8.27)})
sns.scatterplot('weight',show[0],data=df.reset_index(),style='model_year') 
del show[0]
k=1
off=0
for i in show:
    a = plt.twinx()
    a=sns.scatterplot('weight',i,data=df.reset_index(),ax=a, color=list(mcolors.TABLEAU_COLORS)[k],legend=False,style='model_year')
    a.spines['right'].set_position(('outward', off))
    a.yaxis.label.set_color(list(mcolors.TABLEAU_COLORS)[k])
    k+=1
    off+=60

在此处输入图像描述

I want to create a function with the possibility to flexible plot different columns.我想创建一个 function 可以灵活地 plot 不同的列。 Up to now this seems to be quite complicated in plotly to me (no way of just do a loop).到目前为止,这在 plotly 对我来说似乎相当复杂(没办法只做一个循环)。 I would also go with plotly, if there is a good way.如果有好的方法,我也会用 go 和 plotly。

There is actually a good way in Plotly, you can see the code example for the picture below, similar to your matplotlib example in this section of the docs . Plotly 实际上有一个好方法,您可以查看下图的代码示例,类似于文档本节中的matplotlib 示例。

最后结果

I now implemented this using plotly.我现在使用 plotly 实现了这个。

import seaborn as sns
import plotly.graph_objects as go

df=sns.load_dataset("mpg")

show=['mpg','displacement','acceleration']

mcolors=[
    '#1f77b4',  # muted blue
    '#ff7f0e',  # safety orange
    '#2ca02c',  # cooked asparagus green
    '#d62728',  # brick red
    '#9467bd',  # muted purple
    '#8c564b',  # chestnut brown
    '#e377c2',  # raspberry yogurt pink
    '#7f7f7f',  # middle gray
    '#bcbd22',  # curry yellow-green
    '#17becf'   # blue-teal
];


fig = go.Figure()
m=0
for k in df.model_year.unique():
    fig.add_trace(go.Scatter(
        x = df.loc[df.model_year == k]['weight'],
        y = df.loc[df.model_year == k][show[0]],
        name = str(k), 
        mode = 'markers',
        marker_symbol=m,
        marker_line_width=0,
        marker_size=6,
        marker_color=mcolors[0],
    ))
    m+=1

layout = {'xaxis':dict(
        domain=[0,0.7]
        ),
          'yaxis':dict(
            title=show[0],
            titlefont=dict(
                color=mcolors[0]
        ),
        tickfont=dict(
            color=mcolors[0]
        ),
          showgrid=False
          )}
n=2
for i in show[1::]:
    m=0
    for k in df.model_year.unique():
        fig.add_trace(go.Scatter(
            x = df.loc[df.model_year == k]['weight'],
            y = df.loc[df.model_year == k][i],
            name = str(k), 
            yaxis ='y'+str(n),
            mode = 'markers',
            marker_symbol=m,
            marker_line_width=0,
            marker_size=6,
            marker_color=mcolors[n],
            showlegend = False
        ))
        m+=1

    layout['yaxis'+str(n)] = dict(
        title=i,
        titlefont=dict(
            color=mcolors[n]
        ),
        tickfont=dict(
            color=mcolors[n]
            ),
        anchor="free",
        overlaying="y",
        side="right",
        position=(n)*0.08+0.55,
        showgrid=False,
    )
    n+=1

fig.update_layout(**layout)

fig.show()                           

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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