【问题标题】:Python subplots with seaborn or pyplot带有 seaborn 或 pyplot 的 Python 子图
【发布时间】:2023-04-04 18:40:01
【问题描述】:

我是一名学习 python 的 R 程序员,发现在 python 中绘图比 R 困难得多。

我正在尝试编写以下函数,但没有成功。有人可以帮忙吗?

import pandas as pd

#example data
df1 = pd.DataFrame({
        'PC1':[-2.2,-2.0,2.04,0.97],
        'PC2':[0.5,-0.6,0.9,-0.5],
        'PC3':[-0.1,-0.2,0.2,0.8],
        'f1':['a','a','b','b'],
        'f2':['x','y','x','y'],
        'f3':['k','g','g','k']
        })

def drawPCA(df,**kwargs):
    """Produce a 1x3 subplots of scatterplot; each subplot includes two PCs with
    no legend, e.g. subplot 1 is PC1 vs PC2. The legend is on the upper middle of 
    the figure.
    Parameters
    ----------
    df: Pandas DataFrame
        The first 3 columns are the PCs, followed by sample characters.
    kwargs
        To specify hue,style,size, etc. if the plotting uses seaborn.scatterplot; 
        or c,s,etc. if using pyplot scatter
    Example
    ----------
    drawPCA(df1, hue="f1")
    drawPCA(df1, c="f1", s="f2") #if plotting uses plt.scatter
    drawPCA(df1, hue="f1", size="f2",style="f3")
    or more varialbes passable to the actual plotting function
    """    

【问题讨论】:

  • 我不明白f1f2 代表什么。另外,每个图的 x 坐标是多少?或者你想绘制PC1PC2 等等?
  • @MPA,谢谢! f1, f2, f3 只是可以像这样使用的列:
  • @MPA,谢谢! f1, f2, f3 只是可以像seaborn.scatterplot(x="PC1",y="PC2", data=df1,style="f1",hue="f2",size="f3") 一样使用的列。是的,我希望子图 1 是 PC1 与 PC2,子图 2 是 PC1 与 PC3,等等。
  • this 是您要找的吗?

标签: python subplot


【解决方案1】:

这就是我想出来的!只有两个问题:

  1. 是否有参数设置图例水平,而不是使用ncol
  2. 这样运行函数时如何防止图形显示?
fig,ax=drawPCA(df1,hue="f1",style="f2",size="f3")
#may do more changing on the figure.

函数如下:

def drawPCA2(df,**kwargs):
    import matplotlib.pyplot as plt
    import seaborn as sns
    from matplotlib.figure import figaspect

    nUniVals=sum([df[i].unique().size for i in kwargs.values()])
    nKeys=len(kwargs.keys())

    w, h = figaspect(1/3)
    fig1, axs = plt.subplots(ncols=3,figsize=(w,h))
    fig1.suptitle("All the PCs")
    sns.scatterplot(x="PC1",y="PC2",data=df,legend=False,ax=axs[0],**kwargs)
    sns.scatterplot(x="PC1",y="PC3",data=df,legend=False,ax=axs[1],**kwargs)
    sns.scatterplot(x="PC2",y="PC3",data=df,ax=axs[2],label="",**kwargs)
    handles, labels = axs[2].get_legend_handles_labels()
    fig1.legend(handles, labels, loc='lower center',bbox_to_anchor=(0.5, 0.85), ncol=nUniVals+nKeys)  
    axs[2].get_legend().remove()
    fig1.tight_layout(rect=[0, 0.03, 1, 0.9])    

    return fig1,axs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2013-12-26
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    相关资源
    最近更新 更多