如何移除Seaborn PairGrid散点图矩阵右上角的空白子图?
移除散点图矩阵右上角空白子图的解决方案
我希望移除散点图矩阵右上角标记为红色的6个空白子图,尝试了若干参数但未解决问题。以下是我使用的代码:
import seaborn as sns import matplotlib.pyplot as plt import numpy as np # Example dataset iris = sns.load_dataset("iris") # Create PairGrid object with subplots g = sns.PairGrid(iris, height=1.5, aspect=1.2) # Create scatter plots on the lower side g.map_lower(sns.scatterplot) # Add regression line g.map_lower(sns.regplot) # Add histograms g.map_diag(sns.histplot, kde=True) # Then include correlation values for each scatter plot. for i, j in zip(*plt.np.triu_indices_from(g.axes, k=1)): corr_coef = plt.np.corrcoef(iris.iloc[:, i], iris.iloc[:, j])[0][1] g.axes[j, i].annotate(f"R = {corr_coef:.2f}", xy=(.1, .9), xycoords=g.axes[j, i].transAxes) plt.show()
解决方案
要移除右上角的空白子图,只需在代码中添加一段逻辑,定位到这些空白子图并设置其不可见。修改后的完整代码如下:
import seaborn as sns import matplotlib.pyplot as plt import numpy as np # Example dataset iris = sns.load_dataset("iris") # Create PairGrid object with subplots g = sns.PairGrid(iris, height=1.5, aspect=1.2) # Create scatter plots on the lower side g.map_lower(sns.scatterplot) # Add regression line g.map_lower(sns.regplot) # Add histograms g.map_diag(sns.histplot, kde=True) # Then include correlation values for each scatter plot. for i, j in zip(*plt.np.triu_indices_from(g.axes, k=1)): corr_coef = plt.np.corrcoef(iris.iloc[:, i], iris.iloc[:, j])[0][1] g.axes[j, i].annotate(f"R = {corr_coef:.2f}", xy=(.1, .9), xycoords=g.axes[j, i].transAxes) # 隐藏右上角的空白子图 for i, j in zip(*plt.np.triu_indices_from(g.axes, k=1)): g.axes[i, j].set_visible(False) plt.show()
说明
新增的代码通过plt.np.triu_indices_from(g.axes, k=1)精准定位到矩阵右上角(对角线以上的空白区域)的子图,调用set_visible(False)直接隐藏这些空白子图,最终只保留左下角带散点和回归线的图表、对角线的直方图,以及你添加的相关系数标注。
内容的提问来源于stack exchange,提问作者user115916
相关产品推荐
相关产品推荐

