Seaborn/Plotly多个Yax

2024-06-28 19:04:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望在seaborn中使用与matlotlib的示例类似的pandas数据帧,得到一个具有两个以上不同y轴的绘图:https://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

由于它将在函数中使用,我希望能够灵活地选择绘制数据帧的数量和列

不幸的是,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

enter image description here

我想创建一个可以灵活绘制不同列的函数。到目前为止,这似乎是相当复杂的阴谋对我来说(没有办法只是做一个循环)。如果有好办法的话,我也会跟你一起去


Tags: 数据函数import示例dfmodelmatplotlibas
2条回答

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

enter image description here

Plotly中实际上有一种很好的方法,您可以看到下图的代码示例,类似于this section of the docs中的matplotlib示例

final result

相关问题 更多 >