首页 > 解决方案 > Seaborn 示例:具有多个变量但具有多个轴的点图

问题描述

我想绘制以下示例: https ://seaborn.pydata.org/examples/pairgrid_dotplot.html

每列都有一个单独的轴。当前命令:

g.set(xlim=(0, 25), xlabel="Crashes", ylabel="")

设置一个全局轴范围。如何获得个人范围?例如,第一个情节为 0,25,而第二个情节为 0,300?

完整代码如下:

import seaborn as sns
sns.set_theme(style="whitegrid")

# Load the dataset
crashes = sns.load_dataset("car_crashes")

# Make the PairGrid
g = sns.PairGrid(crashes.sort_values("total", ascending=False),
                 x_vars=crashes.columns[:-3], y_vars=["abbrev"],
                 height=10, aspect=.25)

# Draw a dot plot using the stripplot function
g.map(sns.stripplot, size=10, orient="h", jitter=False,
      palette="flare_r", linewidth=1, edgecolor="w")

# Use the same x axis limits on all columns and add better labels
g.set(xlim=(0, 25), xlabel="Crashes", ylabel="")

# Use semantically meaningful titles for the columns
titles = ["Total crashes", "Speeding crashes", "Alcohol crashes",
          "Not distracted crashes", "No previous crashes"]

for ax, title in zip(g.axes.flat, titles):

    # Set a different title for each axes
    ax.set(title=title)

    # Make the grid horizontal instead of vertical
    ax.xaxis.grid(False)
    ax.yaxis.grid(True)

sns.despine(left=True, bottom=True)

标签: pythonseaborn

解决方案


使用已经存在的轴上的循环来单独设置它。
例如,如果您有一个元组列表 (min, max) 以正确的顺序 (as titles) 调用的每一列axes_xlims

# e.g.,
axes_xlims = [(0, 25 + 2 * shift) for shift in range(len(titles))]

for ax, title, ax_xlim, in zip(g.axes.flat, titles, axes_xlim):

    # Set a different title and x limits for each axes
    ax.set(title=title, xlim=ax_xlim)

    # Make the grid horizontal instead of vertical
    ax.xaxis.grid(False)
    ax.yaxis.grid(True)


推荐阅读