如何在 displot 中创建自定义的行和列标签

huangapple go评论63阅读模式
英文:

How to make custom row and column labels in displot

问题

以下是您要翻译的代码部分:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns, numpy as np
from pylab import *

penguins = sns.load_dataset('penguins')

sns.displot(penguins, x='bill_length_mm', col='species', row='island', hue='island',height=3, 
            aspect=2,facet_kws=dict(margin_titles=True, sharex=False, sharey=False),kind='hist', palette='viridis')

plt.show()
英文:

I have the following code using the seaborn library in python that plots a grid of histograms from data from within the seaborn library:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns, numpy as np
from pylab import *

penguins = sns.load_dataset('penguins')

sns.displot(penguins, x='bill_length_mm', col='species', row='island', hue='island',height=3, 
            aspect=2,facet_kws=dict(margin_titles=True, sharex=False, sharey=False),kind='hist', palette='viridis')

plt.show()

This produces the following grid of histograms:
如何在 displot 中创建自定义的行和列标签

And so we have histograms for each species-island combination showing the frequency distribution of different penguin bill lengths, organized in a "grid" of histograms, where the columns of this grid of histograms are organized by species and the rows of this grid are organized by island. And so, I see that seaborn automatically names each column label as the "species" by the argument: col=species. I then see seaborn labels each row as "Count" with the rows organized by island, with different representative "hues" from the argument: hue=island.

What I am trying to do is override these default automatic labels to add my own customization. Specifically what I want to do is replace the top axes labels with just "A", "B", and "C" below a "Species" header, and on the left axis, replace each "Count" instance with the names of each island, but all of these labels in much bigger font size.

This is what I am trying to produce:
如何在 displot 中创建自定义的行和列标签

What I am trying to figure out is, how can I "override" the automatic labelling from the above seaborn arguments so that I can print my custom histogram grid labels, but done in a dynamic way, such that if there were potentially another data set with more islands and more species, the intended labelling organization would still be produced?

答案1

得分: 2

sns.displot 函数返回一个 FacetGrid 对象。该对象允许您使用 set_titles()set_axis_labels() 方法自定义行和列标题。然而,对于您想要实现的非常定制化的图形,恐怕您将不得不直接通过 FacetGrid.axes 来覆盖标签和标题,这将让您访问到一个 matplotlib.Axisndarray

g = sns.displot(penguins, x='bill_length_mm', col='species', row='island', hue='island', height=3,
                aspect=2, facet_kws=dict(margin_titles=True, sharex=False, sharey=False), kind='hist', palette='viridis',
                legend=False)  # 不显示图例

g.set_titles(row_template="")  # 移除右侧的边缘标题

# 重写顶部行轴标题
custom_colnames = ["A", "B", "C"]
for i, ax in enumerate(g.axes[0]):
    ax.set_title(custom_colnames[i], fontsize=14)  # 调整字体大小

# 重写第一列轴的y标签
custom_rownames = penguins["species"].unique()
for i, ax in enumerate(g.axes[:, 0]):
    ax.set_ylabel(custom_rownames[i], fontsize=14, rotation=0, ha="right")

# 移除最后一行轴的x标签
for i, ax in enumerate(g.axes[-1]):
    ax.set_xlabel("")

# 添加一个图形的总标题
plt.gcf().suptitle("物种", y=1.05, fontsize=16)

非常自定义,但这应该可以生成您期望的图形。

英文:

The sns.displot function returns a FacetGrid object. This object let you customize the row and col titles with the methods set_titles() set_axis_labels(). However, with the very custom figure you want to achieve, I'm afraid you'll have to overwrite labels and titles directly through FacetGrid.axes which gives you access to a ndarray of matplotlib.Axis.

g = sns.displot(penguins, x='bill_length_mm', col='species', row='island', hue='island',height=3,
                aspect=2,facet_kws=dict(margin_titles=True, sharex=False, sharey=False), kind='hist', palette='viridis',
                legend=False)  # Do not display the legend

g.set_titles(row_template="")  # Remove the marginal titles on the right side

# Rewrite the top-row axis titles
custom_colnames = ["A", "B", "C"]
for i, ax in enumerate(g.axes[0]):
    ax.set_title(custom_colnames[i], fontsize=14)  # Adjust the fontsize

# Rewrite the first-col axis ylabels
custom_rownames = penguins["species"].unique()
for i, ax in enumerate(g.axes[:, 0]):
    ax.set_ylabel(custom_rownames[i], fontsize=14, rotation=0, ha="right")

# Remove the last-row axis xlabels
for i, ax in enumerate(g.axes[-1]):
    ax.set_xlabel("")

# Add a figure suptitle
plt.gcf().suptitle("Species", y=1.05, fontsize=16)

Very custom, but it should give you the desired figure

如何在 displot 中创建自定义的行和列标签

huangapple
  • 本文由 发表于 2023年3月4日 03:10:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定