Subplot for seaborn boxplot

拥有回忆 提交于 2020-05-07 10:25:29

问题


I have a dataframe like this

import seaborn as sns
import pandas as pd
%pylab inline
df = pd.DataFrame({'a' :['one','one','two','two','one','two','one','one','one','two'], 'b': [1,2,1,2,1,2,1,2,1,1], 'c': [1,2,3,4,6,1,2,3,4,6]})

A single boxplot is OK

sns.boxplot(  y="b", x= "a", data=df,  orient='v' )

But i want to build a subplot for all variables. I do

names = ['b', 'c']
plt.subplots(1,2)
sub = []
for name in names:

    ax = sns.boxplot(  y=name, x= "a", data=df,  orient='v' )
    sub.append(ax)

and i get

how to fix it? thanx for your help


回答1:


We create the figure with the subplots:

f, axes = plt.subplots(1, 2)

Where axes is an array with each subplot.

Then we tell each plot in which subplot we want them with the argument ax.

sns.boxplot(  y="b", x= "a", data=df,  orient='v' , ax=axes[0])
sns.boxplot(  y="c", x= "a", data=df,  orient='v' , ax=axes[1])

And the result is:




回答2:


names = ['b', 'c']
fig, axes =plt.subplots(1,2)

for i,t in enumerate(names):

    sns.boxplot(  y=t, x= "a", data=df,  orient='v',ax=axes[i % 2] )

P.S. @Fabian Schultz asks why my solution should work. I changed my code as below

names = ['b', 'c']
fig, axes =plt.subplots(1,2)
sns.set_style("darkgrid")
flatui = [  "#95a5a6",  "#34495e"]
for i,t in enumerate(names):

    sns.boxplot(  y=t, x= "a", data=df,  orient='v',ax=axes[i % 2] ,  palette= flatui)

This works. Or may be i don't understand your question



来源:https://stackoverflow.com/questions/41384040/subplot-for-seaborn-boxplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!