【问题标题】:Seaborn/Plotly multiple y-axesSeaborn/Plotly 多个 y 轴
【发布时间】: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

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

【问题讨论】:

    标签: python pandas plot plotly seaborn


    【解决方案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 更多的代码,但这些功能是值得的,而且在一天结束时更容易进行更改。跨度>
      猜你喜欢
      • 2022-07-06
      • 2021-03-10
      • 2015-06-09
      • 2015-05-25
      • 2019-11-27
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多