在使用matplotlib绘制的seaborn Pairgrid对象中为每个子图设置x轴标签。

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

Setting xlabels for each suplot in a seaborn Pairgrid object plotted using matplotlib

问题

我正在尝试为seaborn PairGrid对象中的每个子图设置单独的x轴标签但图表不会更新只会显示底部最下面的图的x轴标签

```python
g = sns.PairGrid(dat, x_vars=inputs, y_vars=outputs, hue='variable')

def scatter_plt(x, y, *a, **kw):
    if x.equals(y):
        kw["color"] = (0, 0, 0, 0)
    plt.scatter(x, y, *a, **kw)
    plt.xticks(rotation=90)
    plt.subplots_adjust(wspace=0.4, hspace=0.4)

g.map(scatter_plt)

我尝试了以下方法,但它没有按预期工作,因为我看到与之前相同的图。

xlabels, ylabels = [], []

for ax in g.axes[-1, :]:
    xlabel = ax.xaxis.get_label_text()
    xlabels.append(xlabel)
for ax in g.axes[:, 0]:
    ylabel = ax.yaxis.get_label_text()
    ylabels.append(ylabel)

for i in range(len(xlabels)):
    for j in range(len(ylabels)):
        g.axes[j, i].xaxis.set_label_text(xlabels[i])
        g.axes[j, i].yaxis.set_label_text(ylabels[j])

<details>
<summary>英文:</summary>

I am trying to set individual xlabels for each subplot in a seaborn parigrid object, but the plot wont update and just shows me the xlables for the bottom most plot only.


g = sns.PairGrid(dat,x_vars = inputs, y_vars = outputs, hue = 'variable')

def scatter_plt(x, y, *a, **kw):
if x.equals(y):
kw["color"] = (0, 0, 0, 0)
plt.scatter(x, y,*a, **kw)
plt.xticks(rotation=90)
plt.subplots_adjust(wspace=0.4, hspace=0.4)

g.map(scatter_plt)




I tried the following but it did not work as I saw the same plot as before.


xlabels,ylabels = [],[]

for ax in g.axes[-1,:]:
xlabel = ax.xaxis.get_label_text()
xlabels.append(xlabel)
for ax in g.axes[:,0]:
ylabel = ax.yaxis.get_label_text()
ylabels.append(ylabel)

for i in range(len(xlabels)):
for j in range(len(ylabels)):
g.axes[j,i].xaxis.set_label_text(xlabels[i])
g.axes[j,i].yaxis.set_label_text(ylabels[j])



</details>


# 答案1
**得分**: 1

Seaborn 将这些内部标签设置为不可见,因此您需要显式将它们设置为可见。

以下是代码的翻译部分:

- Seaborn 提供了一些示例数据集,可用于快速测试。在这里,使用`iris`数据集以便于易于重现。
- 只需调用一次`plt.subplots_adjust(...)`,因为它会更改整个图形。与`plt.subplot_adjust()`不同,通常使用`plt.tight_layout()`更容易,因为它尝试优化所有间距。
- 通过使用列表推导式来分配`xlabels`和`ylabels`不仅可以使代码更短,还可以防止错误并使事情更容易更改。
- 类似的推理,在Python中建议最小化显式索引的使用。这就是为什么经常会看到诸如`for i, xlabel in enumerate(xlabels)`这样的构造。

```python
import matplotlib.pyplot as plt
import seaborn as sns

iris = sns.load_dataset('iris')
g = sns.PairGrid(iris, x_vars=iris.columns[0:4], y_vars=iris.columns[0:3], hue='species')

def scatter_plt(x, y, *a, **kw):
    if not x.equals(y):
        plt.scatter(x, y, *a, **kw)
    plt.tick_params(axis='x', rotation=90)

g.map(scatter_plt)

xlabels = [ax.xaxis.get_label_text() for ax in g.axes[-1, :]]
ylabels = [ax.yaxis.get_label_text() for ax in g.axes[:, 0]]

for i, xlabel in enumerate(xlabels):
    for j, ylabel in enumerate(ylabels):
        g.axes[j, i].set_xlabel(xlabel, visible=True)
        g.axes[j, i].set_ylabel(ylabel, visible=True)

plt.tight_layout()
plt.show()

在使用matplotlib绘制的seaborn Pairgrid对象中为每个子图设置x轴标签。

英文:

Seaborn sets these internal labels invisible, so you explicitly need to set them visible again.

Here is how the code could look like. Some details have also changed:

  • Seaborn has some example datasets that can be used for quick testing. Here, the iris dataset is used for easy reproducibility.
  • plt.subplots_adjust(...) only needs to be called once, as it changes the full figure. Instead of plt.subplot_adjust(), plt.tight_layout() often works easier, as it tries to optimize all distances.
  • Assigning the xlabels and ylabels via list comprehension not only makes the code shorter, it also prevents errors and makes things easier to change.
  • In a similar reasoning, in Python it's recommended to minimize the use of explicit indices. That's why often constructions such as for i, xlabel in enumerate(xlabels) are seen.
import matplotlib.pyplot as plt
import seaborn as sns

iris = sns.load_dataset(&#39;iris&#39;)
g = sns.PairGrid(iris, x_vars=iris.columns[0:4], y_vars=iris.columns[0:3], hue=&#39;species&#39;)

def scatter_plt(x, y, *a, **kw):
    if not x.equals(y):
        plt.scatter(x, y, *a, **kw)
    plt.tick_params(axis=&#39;x&#39;, rotation=90)

g.map(scatter_plt)

xlabels = [ax.xaxis.get_label_text() for ax in g.axes[-1, :]]
ylabels = [ax.yaxis.get_label_text() for ax in g.axes[:, 0]]

for i, xlabel in enumerate(xlabels):
    for j, ylabel in enumerate(ylabels):
        g.axes[j, i].set_xlabel(xlabel, visible=True)
        g.axes[j, i].set_ylabel(ylabel, visible=True)

plt.tight_layout()
plt.show()

在使用matplotlib绘制的seaborn Pairgrid对象中为每个子图设置x轴标签。

huangapple
  • 本文由 发表于 2023年1月9日 16:42:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054831.html
匿名

发表评论

匿名网友

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

确定