【问题标题】:Adding y-axis on right side to Ridge Plot in Seaborn将右侧的 y 轴添加到 Seaborn 的 Ridge Plot
【发布时间】:2020-07-19 15:26:12
【问题描述】:

我想在 Ridge 图的右侧添加一个示例 y 轴刻度,以了解所有图的值范围。最好我只想将它添加到其中一个子图中,而不是所有子图中。

我的情节基于 seaborn 的“山脊情节”示例:https://seaborn.pydata.org/examples/kde_ridgeplot.html

我尝试了以下代码,但没有成功:

g.set(yticks=[0,200])
g.set_y_label_position("right")
g.set_ylabels('[Range]',fontsize=9,fontweight="normal")

【问题讨论】:

    标签: python matplotlib seaborn ridgeline-plot


    【解决方案1】:

    如果您想从 FacetGrid 修改一个特定的轴,您可以从列表中获取参考 g.axes

    这就是我的做法

    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})
    
    # Create the data
    rs = np.random.RandomState(1979)
    x = rs.randn(500)
    g = np.tile(list("ABCDEFGHIJ"), 50)
    df = pd.DataFrame(dict(x=x, g=g))
    m = df.g.map(ord)
    df["x"] += m
    
    # Initialize the FacetGrid object
    pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
    g = sns.FacetGrid(df, row="g", hue="g", aspect=15, height=.5, palette=pal)
    
    # Draw the densities in a few steps
    g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)
    g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2)
    g.map(plt.axhline, y=0, lw=2, clip_on=False)
    
    
    # Define and use a simple function to label the plot in axes coordinates
    def label(x, color, label):
        ax = plt.gca()
        ax.text(0, .2, label, fontweight="bold", color=color,
                ha="left", va="center", transform=ax.transAxes)
    
    
    g.map(label, "x")
    
    #
    # Changes from seaborn example below this point
    #
    
    # Set the subplots to overlap
    g.fig.subplots_adjust(hspace=-.25, right=0.9)
    
    # Remove axes details that don't play well with overlap
    g.set_titles("")
    #g.set(yticks=[])
    g.despine(bottom=True, left=True, right=False, top=True, offset=5)
    
    for ax in g.axes.ravel():
        if ax.is_first_row():  # can use .is_last_row() to show spine on the bottom plot instead
            ax.yaxis.tick_right()
            ax.yaxis.set_label_position("right")
            ax.set_ylabel("MW")
        else:
            ax.spines['right'].set_visible(False)
            [l.set_visible(False) for l in ax.get_yticklabels()]  # necessary because y-axes are shared
    

    【讨论】:

    • 谢谢,这行得通。我将如何在该侧添加 yaxislabel?我在if 语句中尝试了这个:ax.yaxis.set_label_text('MW') 但标签位于左侧。
    • 使用ax.yaxis.set_label_position("right")。我已经修改了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多