seaborn.boxplot#
Draw a box plot to show distributions with respect to categories.
A box plot (or box-and-whisker plot) shows the distribution of quantitative data in a way that facilitates comparisons between variables or across levels of a categorical variable. The box shows the quartiles of the dataset while the whiskers extend to show the rest of the distribution, except for points that are determined to be “outliers” using a method that is a function of the inter-quartile range.
This function always treats one of the variables as categorical and draws data at ordinal positions (0, 1, … n) on the relevant axis, even when the data has a numeric or date type.
See the tutorial for more information.
Parameters : data DataFrame, array, or list of arrays, optional
Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form.
x, y, hue names of variables in data or vector data, optional
Inputs for plotting long-form data. See examples for interpretation.
order, hue_order lists of strings, optional
Order to plot the categorical levels in; otherwise the levels are inferred from the data objects.
orient “v” | “h”, optional
Orientation of the plot (vertical or horizontal). This is usually inferred based on the type of the input variables, but it can be used to resolve ambiguity when both x and y are numeric or when plotting wide-form data.
color matplotlib color, optional
Single color for the elements in the plot.
palette palette name, list, or dict
Colors to use for the different levels of the hue variable. Should be something that can be interpreted by color_palette() , or a dictionary mapping hue levels to matplotlib colors.
saturation float, optional
Proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color.
width float, optional
Width of a full element when not using hue nesting, or width of all the elements for one level of the major grouping variable.
dodge bool, optional
When hue nesting is used, whether elements should be shifted along the categorical axis.
fliersize float, optional
Size of the markers used to indicate outlier observations.
linewidth float, optional
Width of the gray lines that frame the plot elements.
whis float, optional
Maximum length of the plot whiskers as proportion of the interquartile range. Whiskers extend to the furthest datapoint within that range. More extreme points are marked as outliers.
ax matplotlib Axes, optional
Axes object to draw the plot onto, otherwise uses the current Axes.
kwargs key, value mappings
Other keyword arguments are passed through to matplotlib.axes.Axes.boxplot() .
Returns : ax matplotlib Axes
Returns the Axes object with the plot drawn onto it.
A combination of boxplot and kernel density estimation.
A scatterplot where one variable is categorical. Can be used in conjunction with other plots to show each observation.
A categorical scatterplot where the points do not overlap. Can be used with other plots to show each observation.
Combine a categorical plot with a FacetGrid .
Draw a single horizontal boxplot, assigning the data directly to the coordinate variable:
Зачем вам боксплот?
Сегодня поговорим про боксплоты и зачем они вам нужны. Боксплоты (box plots), которые переведены на русский как “ящик с усами” или “диаграмма размаха”. Ящик с усами для меня вообще что-то странное, поэтому я почти всегда называют их боксплоты. Придумал этот график Джон Тьюки еще в 70-е. Людям, хоть чуть знакомым со статистикой, его имя явно знакомо. А еще он придумал слова software и bit, ну и box plot разумеется.
Боксплот сделан для того, чтобы показывать распределение, но график уникальный, потому что помимо распределения он показывает медиану, квартили, минимум, максимум и выбросы. Неплохо для одного-то графика, да? Где, что находится можно посмотреть на картинке.
Зачем он вам? Это один из немногих графиков, позволяющий показать выбросы, а это то, что очень сильно влияет на ваи графики. На всякий случай напомню, что выбросы — это значения, очень сильно выделяющиеся из всей остальной массы ваших данных. А теперь представьте барчарт, который бы эти выбросы просто сложил. И вот покажу вам немного переделанный пример применения боксплотов, с которым я сама столкнулась и не дала их в обиду!
Допустим у вас есть контент-план (как у нормальной группы, не как у меня). И в нем у вас есть три типа постов, которые вы делаете, допустим: новости, шуточки и обзоры графиков. По ним собирается определенное количество лайков с каждого, и вы знаете, что новости обычно получают 5–7 лайков, шуточки чуть больше, а обзоры “не заходят” (только за редким исключением). Вот так это выглядело бы на боксплоте. Медианное количество лайков у новостей — 5, у шуточек — 6, а у обзоров — 2. А теперь смотрим на часть обзоров и видим сверху выбросы, две замечательные точки, которые говорят нам о том, что есть некоторые обзоры, которые “выстреливают” куда лучше остального контенте. То есть обзоры в принципе идут так себе, но если написать что-то полезное, то лайков соберете больше, чем с шуточек. Таким образом, вы увидели то, чего не увидели бы, не посмотрев на выбросы, и решили бы, что обзоры просто не очень и надо от них отказаться. А на самом деле, нужно понять, что это за выбросы и про что в выбросных постах написано.
На картинке есть еще пример, как из этого выглядел бы барчарт по сумме или даже среднему количеству лайков. Так что не бойтесь использовать разные графики, если они способны показать гораздо больше. Возможно, вам придется потратить время на их объяснение, но вы сможете увидеть то, чего не видели прежде
Box plot visualization with Pandas and Seaborn
Box Plot is the visual representation of the depicting groups of numerical data through their quartiles. Boxplot is also used for detect the outlier in data set. It captures the summary of the data efficiently with a simple box and whiskers and allows us to compare easily across groups. Boxplot summarizes a sample data using 25th, 50th and 75th percentiles. These percentiles are also known as the lower quartile, median and upper quartile.
A box plot consist of 5 things.
- Minimum
- First Quartile or 25%
- Median (Second Quartile) or 50%
- Third Quartile or 75%
- Maximum
To download the dataset used, click here.
Draw the box plot with Pandas:
One way to plot boxplot using pandas dataframe is to use boxplot() function that is part of pandas library.
What is box plot ?
This blog talks about what is box plot, understanding box plot with help of probability density function (pdf), how to make a box plot by python module matplotlib and how to interprete a boxplot.
What should we do if we are curious about the average volume of basket? It’s not enough if we only sum volume of all baskets and divide it by baskets’ amount. We can also explore it with box plot. In this blog, I’ll talk about box plot with following points:
- What is box plot ?
- Understanding box plot with help of probability density function (pdf)
- How to make a box plot by python module matplotlib ?
- How to interprete a boxplot ?
What is box plot ?
Box plot is like the plot above. In descriptive statistics, a box plot or boxplot is a method for graphically depicting groups of numerical data through their quartiles. Box plot describes data distribution with 5 measures: minimum, first quartile (Q1), median, third quartile(Q3) and maximum.
- Interquartile range (IQR): 25th to 75th percentile
- Median (Q2): 50th percentile, the middle value of the dataset
- First quartile (Q1): 25th percentile, the middle number between the smallest value (not the “minimum”) and the median of the dataset.
- Third quartile (Q3): 75th percentile, the middle number between the median and the highest value (not the “maximum”) of the dataset.
- Minimum: Q1 — 1.5 * IQR
- Maximum: Q3 + 1.5 * IQR
Understanding box plot with help of probability density function (pdf)
This graph compares the box plot to probability density function (pdf) for a normal distribution. Here I’ll simply interprete the comparison: 50% values of the dataset are in IQR, 7% values are outliers, other values are either between “minimum” and Q1, or between Q3 and “maximum”. If you are interested in detail, you will find it here.
How to make a box plot by python module matplotlib ?
It’s simple to make a box plot with python module matplotlib , we can apply box() function and specify the input data. Suppose that wo_service and with_service are 2 dataframes that contain volume of each basket. This plot describes the volume distribution for baskets that contain and don’t contain certain product(s).
How to interprete a boxplot ?
Now we can answer the question at beginning of this blog: what the average volume of basket? Thanks to the box plot above, we can not only understand the volumes’ distribution, but also get the average volume and compare the value between baskets without service and with service, find that the new service brings more sales.
Conclusion
In this blog, I introduced what is box plot, understanding box plot with help of probability density function (pdf), how to make a box plot by python module matplotlib and how to interprete a boxplot. Hope it’s useful for you 🙂