Now that we know the basics of seaborn syntax and have seen some of the plots we can make, let’s start coding! For the rest of the lesson, we’ll spend time creating each of the plots we previewed in the last exercise.
Let’s start with a bar plot. After importing seaborn as
sns, we make a bar plot using
sns.barplot(). We set
data to the name of our DataFrame. The bars are plotted vertically by default, so we set
x to the column name of data with categories or groups so these are displayed along the x-axis. We set
y (bar height on the y-axis) to the column name of data measured in numbers. This column’s data will be aggregated for each group of the
The following code produces a vertical bar plot of mean
sales_totals for each
df = pd.read_csv('restaurant_data.csv') sns.barplot(data=df, x='server', y='sales_totals')
The default aggregation method is to take the mean of each group, but we can change this by setting the
estimator parameter to another method. Many functions from the NumPy library can be called like
np.std. This code will show us the same plot but with the median for each group instead of the mean.
import numpy as np sns.barplot(data=df, x='server', y='sales_totals', estimator=np.median)
We’ll see more special parameters like
estimator as we look at other plot types in the next exercises.
One last feature to note is that seaborn plots a line on each bar by default. These lines are error bars set at a 95% confidence interval. We can hide these bars by setting the
ci parameter to
sns.barplot(data=df, x='server', y='sales_totals', ci='None')
Note: For seaborn version >= 0.12.0, the
ci parameter is deprecated in favor of the
errorbar parameter. Set
errorbar=None for later versions of seaborn.
After running the first two code cells and viewing the
fires dataset, write the code to make a bar plot of the mean number of
firespots for each
state. Put the state names on the y axis so that the bars are horizontal in the plot.
Create the same plot as you did in step 1, but use median values instead of mean values.
Create the same plot of medians from step 2, but remove the error bars.