Python 使用Seaborn在一个图形中绘制多个不同的绘图
我正试图利用seaborn从《统计学习导论》一书中重现以下情节 我特别想使用seaborn的Python 使用Seaborn在一个图形中绘制多个不同的绘图,python,matplotlib,seaborn,Python,Matplotlib,Seaborn,我正试图利用seaborn从《统计学习导论》一书中重现以下情节 我特别想使用seaborn的lmplot创建前两个绘图,并使用boxplot创建第二个绘图。主要的问题是lmplot创建了一个FaceGrid,这迫使我为boxplot添加另一个matplotlib轴。我想知道是否有更简单的方法来实现这一点。下面,我必须做相当多的手动操作,以获得所需的绘图 seaborn_grid = sns.lmplot('value', 'wage', col='variable', hue='educatio
lmplot
创建前两个绘图,并使用boxplot
创建第二个绘图。主要的问题是lmplot创建了一个FaceGrid
,这迫使我为boxplot添加另一个matplotlib轴。我想知道是否有更简单的方法来实现这一点。下面,我必须做相当多的手动操作,以获得所需的绘图
seaborn_grid = sns.lmplot('value', 'wage', col='variable', hue='education', data=df_melt, sharex=False)
seaborn_grid.fig.set_figwidth(8)
left, bottom, width, height = seaborn_grid.fig.axes[0]._position.bounds
left2, bottom2, width2, height2 = seaborn_grid.fig.axes[1]._position.bounds
left_diff = left2 - left
seaborn_grid.fig.add_axes((left2 + left_diff, bottom, width, height))
sns.boxplot('education', 'wage', data=df_wage, ax = seaborn_grid.fig.axes[2])
ax2 = seaborn_grid.fig.axes[2]
ax2.set_yticklabels([])
ax2.set_xticklabels(ax2.get_xmajorticklabels(), rotation=30)
ax2.set_ylabel('')
ax2.set_xlabel('');
leg = seaborn_grid.fig.legends[0]
leg.set_bbox_to_anchor([0, .1, 1.5,1])
产生
数据帧的示例数据:
df_melt = {'education': {0: '1. < HS Grad',
1: '4. College Grad',
2: '3. Some College',
3: '4. College Grad',
4: '2. HS Grad'},
'value': {0: 18, 1: 24, 2: 45, 3: 43, 4: 50},
'variable': {0: 'age', 1: 'age', 2: 'age', 3: 'age', 4: 'age'},
'wage': {0: 75.043154017351497,
1: 70.476019646944508,
2: 130.982177377461,
3: 154.68529299562999,
4: 75.043154017351497}}
df_wage={'education': {0: '1. < HS Grad',
1: '4. College Grad',
2: '3. Some College',
3: '4. College Grad',
4: '2. HS Grad'},
'wage': {0: 75.043154017351497,
1: 70.476019646944508,
2: 130.982177377461,
3: 154.68529299562999,
4: 75.043154017351497}}
df_melt={'education':{0:'1.
一种可能是不使用lmplot()
,而是直接使用regplot()
regplot()
使用ax=
在作为参数传递的轴上打印
您失去了根据某个变量自动分割数据集的能力,但是如果您事先知道要生成的绘图,这应该不会是问题
大概是这样的:
导入matplotlib.pyplot作为plt
导入seaborn作为sns
图,axs=plt子批次(ncols=3)
sns.regplot(x='value',y='wage',data=df\u melt,ax=axs[0])
sns.regplot(x='value',y='wage',data=df\u melt,ax=axs[1])
sns.boxplot(x='education',y='wage',data=df\u melt,ax=axs[2])
谢谢,我想我正在寻找一种更通用的解决方案,该解决方案允许镶嵌面网格包含一个额外的空白轴,以便将来进行其他打印。使用lmplot可能没有这样做的方法。我想您应该使用PairGrid
。