pandas 如何调整seaborn中的子图大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41659188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to adjust subplot size in seaborn?
提问by DSG
%matplotlib inline
fig, axes = plt.subplots(nrows=2, ncols=4)
m = 0
l = 0
for i in k:
if l == 4 and m==0:
m+=1
l = 0
data1[i].plot(kind = 'box', ax=axes[m,l], figsize = (12,5))
l+=1
This outputs subplots as desired.
这会根据需要输出子图。
But when trying to achieve it through seaborn, subplots are stacked close to each other, how do I change size of each subplot?
但是当试图通过 seaborn 实现它时,子图彼此靠近堆叠,我如何更改每个子图的大小?
fig, axes = plt.subplots(nrows=2, ncols=4)
m = 0
l = 0
plt.figure(figsize=(12,5))
for i in k:
if l == 4 and m==0:
m+=1
l = 0
sns.boxplot(x= data1[i], orient='v' , ax=axes[m,l])
l+=1
回答by Ted Petrou
Your call to plt.figure(figsize=(12,5))
is creating a new empty figure different from your already declared fig
from the first step. Set the figsize
in your call to plt.subplots
. It defaults to (6,4) in your plot since you did not set it. You already created your figure and assigned to variable fig
. If you wanted to act on that figure you should have done fig.set_size_inches(12, 5)
instead to change the size.
您对 的调用plt.figure(figsize=(12,5))
正在创建一个新的空图,与您fig
在第一步中已经声明的不同。将figsize
通话中的设置为plt.subplots
。由于您没有设置它,它在您的图中默认为 (6,4)。您已经创建了图形并分配给了变量fig
。如果你想对那个数字采取行动,你应该fig.set_size_inches(12, 5)
改变大小。
You can then simply call fig.tight_layout()
to get the plot fitted nicely.
然后,您可以简单地调用fig.tight_layout()
以很好地拟合该图。
Also, there is a much easier way to iterate through axes by using flatten
on your array of axes
objects. I am also using data directly from seaborn itself.
此外,通过flatten
在axes
对象数组上使用,还有一种更简单的方法来遍历轴。我也直接使用来自 seaborn 本身的数据。
# I first grab some data from seaborn and make an extra column so that there
# are exactly 8 columns for our 8 axes
data = sns.load_dataset('car_crashes')
data = data.drop('abbrev', axis=1)
data['total2'] = data['total'] * 2
# Set figsize here
fig, axes = plt.subplots(nrows=2, ncols=4, figsize=(12,5))
# if you didn't set the figsize above you can do the following
# fig.set_size_inches(12, 5)
# flatten axes for easy iterating
for i, ax in enumerate(axes.flatten()):
sns.boxplot(x= data.iloc[:, i], orient='v' , ax=ax)
fig.tight_layout()
Without the tight_layout
the plots are slightly smashed together. See below.
没有tight_layout
地块被轻微地砸在一起。见下文。