最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to draw y-axis title dynamically with template approach in Seaborn FacetGrid - Stack Overflow

programmeradmin0浏览0评论

I have a DataFrame with a column containing two types of metrics. I plotted it using seaborn.FacetGrid, setting one metric per row. My goal is to rename the y-axis label for each facet to match the corresponding metric.

import pandas as pd
import numpy as np
import seaborn as sns

# Generate random data
categories = [1] * 5 + [2] * 5
n = len(categories) # Number of rows

data = {
    "model": np.random.choice(categories, size=n, replace=False),  # 1 = RF, 2 = SVM
    "metric": np.random.choice(categories, size=n, replace=False), # 1 = kappa, 2 = accuracy
    "predictors": np.random.choice(categories, size=n, replace=False),
    "value": np.random.uniform(0.7, 1, size=n)
}

# Convert to DataFrame
df = pd.DataFrame(data)

# Replace numerical categories with text labels
df["model"] = df["model"].map({1: "RF", 2: "SVM"}).astype("category")
df["metric"] = df["metric"].map({1: "kappa", 2: "accuracy"}).astype("category")

g = sns.FacetGrid(df, col="model", row="metric", hue="predictors", palette="tab10")
g.map(sns.barplot, "predictors", "value", legend=True, order=sorted(df['predictors']))
g.set_axis_labels(x_var="Predictors ID")
g.set_titles(template="{row_name}, {col_name}")
g.add_legend()

I know that, as mentioned in this post, the labels can be modified by accessing Matplotlib options.

for i, model in enumerate(np.sort(pd.unique(df["metric"]))):
    g.axes[i,0].set_ylabel(model)

However, I want to know if there is a method within Seaborn's FacetGrid—similar to set_titles with the template argument—to directly modify the y-axis labels.

Is there a built-in way to achieve this in Seaborn, or do I need to manually update each subplot’s y-axis label using Matplotlib?

发布评论

评论列表(0)

  1. 暂无评论