Seaborn/Plotly 多个 y 轴

Posted

技术标签:

【中文标题】Seaborn/Plotly 多个 y 轴【英文标题】:Seaborn/Plotly multiple y-axes 【发布时间】:2020-07-19 10:47:29 【问题描述】:

我想使用类似于 matlotlib 示例的 pandas 数据框在 seaborn 中获得一个具有两个以上不同 y 轴的图:https://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

由于它将在函数中使用,我希望灵活地选择要绘制 Pandas 数据框的数量和列。

不幸的是,Seaborn 似乎只移动了最后添加的比例。 这是我想要对 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

我想创建一个可以灵活绘制不同列的函数。到目前为止,这对我来说似乎很复杂(不可能只做一个循环)。如果有好的方法,我也会选择。

【问题讨论】:

【参考方案1】:

我现在使用 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()                           

【讨论】:

【参考方案2】:

其实Plotly里面有一个很好的方法,可以看下图的代码示例,和你this section of the docs中的matplotlib示例类似。

【讨论】:

据我了解,在处理 pandas 数据帧方面,向 Plotly 图形添加跟踪并不像使用 Plotly Express 或 Seaborn 那样优雅和简单。诸如通过列的值定义标记样式之类的事情使它变得更加复杂。遗憾的是失去了这个特定问题的所有实用程序。 我会说这取决于你如何使用它。 here 中描述的命令式替代方案在优雅方面对我来说很有意义,它可能比 Express 更多的代码,但这些功能是值得的,而且在一天结束时更容易进行更改。跨度>

以上是关于Seaborn/Plotly 多个 y 轴的主要内容,如果未能解决你的问题,请参考以下文章

Pandas+Seaborn+Plotly:联手探索苹果AppStore

QwtPlot - 多个 Y 轴

r 将多个ggplot2图与一个共同的x轴和不同的y轴对齐,每个轴都有不同的y轴标签。

Plotly Python:在具有多个 Y 轴的分组条形图中对齐 X 轴

Nvd3.js - 向累积图表添加多个 y 轴

echarts实现多个y轴