Seaborn Barplot – sns.barplot() 20 Parameters | Python Seaborn Tutorial

If you have x and y variable dataset and want to find a relationship between them using bar graph then seaborn barplot will help you. The seaborn sns.barplot() function draws barplot conveniently.

In the seaborn histogram tutorial, we learned how to draw histogram using sns.distplot() function? But it doesn’t support categorical dataset that’s a reason, we are using sns barplot.

Keep in mind sns is short name given to seaborn libary.

What is seaborn Barplot?

Let’s try to understand the bar graph first.

  • Bar graph or Bar Plot: Bar Plot is a visualization of x and y numeric and categorical dataset variable in a graph to find the relationship between them.

The python seaborn library use for data visualization, so it has sns.barplot() function helps to visualize dataset in a bar graph.

Now, in your mind, how to draw barplot using seaborn barplot? the question arrived then follow me practically.

Plotting Barplot using Seaborn

Import Libraries

Here, we importing seaborn and numpy library.

# Import libraries
import seaborn as sns # for data visualization
import numpy as np # for numeric computing
import matplotlib.pyplot as plt # for data visualization

Load dataset to draw barplot

To draw barplot use x and y variable dataset and one variable must be numeric. You can use your business dataset but here, we are load “tips.csv” DataFrame from GitHub seaborn repository using sns.load_dataset() function.

# load dataset from GitHub seaborn repository
tips_df = sns.load_dataset("tips")
print(tips_df)

Output >>>

total_bill	tip	sex	smoker	day	time	size
0	16.99	1.01	Female	No	Sun	Dinner	2
1	10.34	1.66	Male	No	Sun	Dinner	3
2	21.01	3.50	Male	No	Sun	Dinner	3
3	23.68	3.31	Male	No	Sun	Dinner	2
4	24.59	3.61	Female	No	Sun	Dinner	4
5	25.29	4.71	Male	No	Sun	Dinner	4
6	8.77	2.00	Male	No	Sun	Dinner	2
7	26.88	3.12	Male	No	Sun	Dinner	4
8	15.04	1.96	Male	No	Sun	Dinner	2
9	14.78	3.23	Male	No	Sun	Dinner	2
10	10.27	1.71	Male	No	Sun	Dinner	2
.........
.........
231	15.69	3.00	Male	Yes	Sat	Dinner	3
232	11.61	3.39	Male	No	Sat	Dinner	2
233	10.77	1.47	Male	No	Sat	Dinner	2
234	15.53	3.00	Male	Yes	Sat	Dinner	2
235	10.07	1.25	Male	No	Sat	Dinner	2
236	12.60	1.00	Male	Yes	Sat	Dinner	2
237	32.83	1.17	Male	Yes	Sat	Dinner	2
238	35.83	4.67	Female	No	Sat	Dinner	3
239	29.03	5.92	Male	No	Sat	Dinner	3
240	27.18	2.00	Female	Yes	Sat	Dinner	2
241	22.67	2.00	Male	Yes	Sat	Dinner	2
242	17.82	1.75	Male	No	Sat	Dinner	2
243	18.78	3.00	Female	No	Thur	Dinner	2

244 rows × 7 columns

sns.barplot() function

sns.barplot() function belongs to seaborn data visualization library to draw barplot.

Syntax: sns.barplot(
                                     x=None,
                                     y=None,
                                     hue=None,
                                     data=None,
                                     order=None,
                                     hue_order=None,
                                     estimator=<function mean at 0x0000026F155D02F0>,
                                     ci=95,
                                     n_boot=1000,
                                     units=None,
                                     orient=None,
                                     color=None,
                                     palette=None,
                                     saturation=0.75,
                                     errcolor=’.26′,
                                     errwidth=None,
                                     capsize=None,
                                     dodge=True,
                                     ax=None,
                                     **kwargs,
                                    )

# Plot barplot
sns.barplot()

Output >>>

seaborn empty barplot

1. sns.barplot() x, y parameters

  • Pass value as variables name of dataset or vector data, optional

Plotting barplot of ‘day‘ and ‘total_bill‘ from tips DataFrame.

# Plot tips_df.day &amp; tips_df.total_bill barplot
sns.barplot(x = tips_df.day, y = tips_df.total_bill)

Output >>>

seaborn barplot

This bar plot show maximum bill pay on Sunday and minimum on Friday.

2. sns.barplot() hue parameter

  • Pass value as variables name of dataset or vector data, optional

Observe “tips” DataFrame, in this DataFrame sex categorical variable, contain Male and Female and you want to plot its per day barplot then hue parameter will help.

# Devide barplot using hue parameter
sns.barplot(x = tips_df.day, y = tips_df.total_bill, hue = tips_df.sex)

Output >>>

seaborn barplot hue

3. sns.barplot() data parameter

  • Pass value as DataFrame, array, or list of arrays, optional

In the above code snippet, used “tips_df.” for getting a particular column but you want to stop it then sns.barplot data parameter will help you.

# Pass dataset using data parameter
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df)

Output >>>

sns barplot data

4. sns.barplot() order parameter

  • Pass list of string, optional

In the above bar plot, tips_df.day x categorical variable contains 4 days in order [‘Thur’, ‘Fri’, ‘Sat’, ‘Sun’] but you want to change its order then use it.

# modify the order of day
order = ['Sun', 'Thur', 'Fri', 'Sat']

sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, order = order)

Output >>>

sns barplot order

5. sns.barplot() hue_order parameter

  • Pass list of string, optional

To change hue order then use it. In above graph hue order is [‘Male’, ‘Female’] but your requirement [‘Female, ‘Male’] then follow bellow code snippet.

#Modify hue order
hue_order = ['Female', 'Male']

sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, hue_order = hue_order)

Output >>>

sns barplopt hue_order

6. sns.barplot() estimator parameter

  • Pass value as callable that maps vector -> scalar, optional

It accepts NumPy statistical function like mean, median, max, min to estimate within each categorical bin. In a simple way, you want to set ymax by statistical function then use it.

# estimate y variable value and then plot
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, estimator= np.max)

Note: You have to import numpy first then run it.

Output >>>

sns barplot estimator

7. sns.barplot() ci parameter

  • Pass value as float or “sd” or None, optional

Size of ci (confidence intervals) to draw around estimated values. In simple word to increase errorbar then pass value between 0 to 100.

# set error bar size
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, ci = 20)

Output >>>

sns.barplot() ci

8. sns.barplot() n_boot parameter

  • Pass value as int, optional

n_boot means the number of bootstrap iterations to use when computing confidence intervals.

# set error bar 
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df,  n_boot=2)

Output >>>

sns.barplot() n_boot

9. sns.barplot() orient parameter

  • Pass string value “v” for vertical barplot or “h” for horizontal, optional

If one variable is categorical from both then no need to use orient parameter for draw seaborn horizontal barplot. Just pass y variable as a categorical.

# set barplot as horizontal
sns.barplot(y = 'day', x = 'total_bill', hue = 'sex',
           data = tips_df,)

Output >>>

seaborn barplot horizontal

If, both x and y variable are numeric type then seaborn barplot orient parameter help to plot vertical or horizontal barplot.

This is the seaborn horizontal barplot.

# set barplot as horizontal
sns.barplot(x ='total_bill', y = 'size', hue = 'sex', data = tips_df,
           orient='h')

Output >>>

seaborn barplot orient horizontal

10. sns.barplot() color parameter

Use to change seaborn barplot color. Here, we pass green color code as a string.

# set color
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, color="g")

Output >>>

seaborn barplot color

11. sns.barplot() palette parameter

  • Pass value as palette name, list, or dict, optional
Palette Values : 

Possible values are: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG,
 PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r,
 YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r,
 gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, icefire, icefire_r, inferno, inferno_r, jet, jet_r, magma, magma_r, mako,
 mako_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, rocket, rocket_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r,
 twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, vlag, vlag_r, winter, winter_r

Use to change the color of bars and hue order by palette or you can say color map.

# set color map or palette
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, palette="magma")

Output >>>

sns barplot palette

12. sns.barplot() saturation parameter

  • Pass value as float, optional

Use for color saturation.

# set saturation of barplot
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, saturation=.3)

Output >>>

sns barplot saturation

13. sns.barplot() errcolor parameter

  • Pass matplotlib color value

To change the color of the error bar.

#set color of error bar
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, errcolor='0.5')

Output >>>

sns barplot errcolor

14. sns.barplot() errwidth parameter

  • Pass value as float, optional

To change the width of the error bar.

# set width of error bar
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, errwidth= 12)

Output >>>

sns barplot errwidth

15. sns.barplot() capsize parameter

  • Pass value as float, optional

To change the capsize of the error bar.

# set cap size of error bar
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, capsize=1)

Output >>>

sns barplot capsize

16. sns.barplot() dodge parameter

  • Pass value as bool, optional

To shift seaborn barplot hue category bar in a single bar then pass bool True value.

# shift hue categorical variable bar bar in one bar
sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df, dodge= False)

Output >>>>

barplot dodge

17. sns.barplot() kwargs parameter

  • Pass dictionary in key and value pair.

Seaborn bar plot Keyword arguments (kwargs) help to give an artistic look to the bar graph. You can pass plt.bar() keyword arguments to it. Check out the matplotlib bar char article.

Here, we are using some barplot kwargs like:

  • alpha
  • linestyle
  • linewidth
  • edgecolor
  • etc

but I recommend you use more for an artistic look.

# Keyword Arguments parameter
kwargs = {'alpha':0.9, 'linestyle':':', 'linewidth':5, 'edgecolor':'k'}

sns.barplot(x = 'day', y = 'total_bill', hue = 'sex',
           data = tips_df,**kwargs)

output >>>

barplot keyword arguments

You can pass barplot keyword arguments directly as a parameter.

# Pass Keyword  argument as parameter
sns.set() # for darkgrid background
sns.barplot(x = 'day', y = 'total_bill', 
           data = tips_df, alpha =.9, linestyle = "-.", linewidth = 3,
           edgecolor = "g")

output >>>

seaborn bar plot  kwargs

18. sns.barplot() ax parameter

  • Pass matplotlib Axes, optional

Using axes (ax) barplot parameter set lots of things like:

  • title for barplot
  • xlabel for barplot
  • ylabel for barplot
# Axes parameter
sns.set()
ax = sns.barplot(x = 'day', y = 'total_bill', 
           data = tips_df, alpha =.9, linestyle = "-.", linewidth = 3,
           edgecolor = "g")

ax.set(title = "Barplot of Tips DataFrame",
      xlabel = "Days",
      ylabel = "Total Bill")

output >>>

sns.barplot() axes

Example of Seaborn Barplot

Till now, we used all barplot parameter and its time to use them together because to show it the professional way. In bellow, barplot example used some other functions like:

  • sns.set – for background dark grid style
  • plt.figure() – for figure size
  • plt.title() – for barplot title
  • plt.xlabel() – for x-axis label
  • plt.ylabel() – for y-axis label
  • plt.savefig() – for save figure
  • plt.show() – for show image only
# Example of Seaborn Barplot
sns.set()
plt.figure(figsize = (16,9))

sns.barplot(x = 'day', y = 'total_bill', 
           data = tips_df, alpha =1, linestyle = "-.", linewidth = 3,
           edgecolor = "k")

plt.title("Barplot of Days and Total Bill", fontsize = 20)
plt.xlabel("Days", fontsize = 15)
plt.ylabel("Total Bill", fontsize = 15)

plt.savefig("Barplot of Days and Total Bill")
plt.show()

Output >>>

Example of seaborn barplot

Conclusion

In the seaborn barplot blog, we learn how to plot one and multiple bar plot with a real-time example using sns.barplot() function. Along with that used different functions and different parameter. We suggest you make your hand dirty with each and every parameter of the above function because This is the best coding practice. Still, you didn’t complete matplotlib tutorial then I suggest you do it.

Download above barplot source code in Jupyter NoteBook file formate.

Leave a Reply

Top