简体   繁体   中英

Plotting a boxplot and histogram side by side with seaborn

I'm trying to plot a simple box plot next to a simple histogram in the same figure using seaborn (0.11.2) and pandas (1.3.4) in a jupyter notebook (6.4.5).

I've tried multiple approaches with nothing working.

fig, ax = plt.subplots(1, 2)
sns.boxplot(x='rent', data=df, ax=ax[0])
sns.displot(x='rent', data=df, bins=50, ax=ax[1])

在箱线图旁边添加额外的网格。

There is an extra plot or grid that gets put next to the boxplot, and this extra empty plot shows up any time I try to create multiple axes.

Changing:

fig, ax = plt.subplots(2)

Gets:

额外的空白图现在位于底部

Again, that extra empty plot next to the boxplot, but this time below it.

Trying the following code:

fig, (axbox, axhist) = plt.subplots(1,2)
sns.boxplot(x='rent', data=df, ax=axbox)
sns.displot(x='rent', data=df, bins=50, ax=axhist)

Gets the same results.

Following the answer in this post , I try:

fig, axs = plt.subplots(ncols=2)
sns.boxplot(x='rent', data=df, ax=axs[0])
sns.displot(x='rent', data=df, bins-50, ax=axs[1])

results in the same thing:

在此处输入图像描述

If I just create the figure and then the plots underneath:

plt.figure()
sns.boxplot(x='rent', data=df)
sns.displot(x='rent', data=df, bins=50)

It just gives me the two plots on top of each other, which I assume is just making two different figures.

I'm not sure why that extra empty plot shows up next to the boxplot when I try to do multiple axes in seaborn.

If I use pyplot instead of seaborn, I can get it to work:

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
ax1.hist(df['rent'], bins=50)
ax2.boxplot(df['rent'])

Results in:

一张图上有两个图

The closest I've come is to use seaborn only on the boxplot, and pyplot for the histogram:

plt.figure(figsize=(8, 5))
plt.subplot(1, 2, 1)
sns.boxplot(x='rent', data=df)
plt.subplot(1, 2, 2)
plt.hist(df['rent'], bins=50)

Results:

两张图,一张图。

What am I missing? Why can't I get this to work with two seaborn plots on the same figure, side by side (1 row, 2 columns)?

Try this function:

def creating_box_hist(column, df):
    # creating a figure composed of two matplotlib.Axes objects (ax_box and ax_hist)
    f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={"height_ratios": (.15, .85)})    

    # assigning a graph to each ax
    sns.boxplot(df[column], ax=ax_box)
    sns.histplot(data=df, x=column, ax=ax_hist)

    # Remove x axis name for the boxplot
    ax_box.set(xlabel='')
    plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM