No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python Boxplot matplotlib Example

by Khaleel O.
January 4, 2022
in Python
Reading Time: 4 mins read
A A
Python Boxplot matplotlib Example
Python Boxplot matplotlib Example

Hi! Let’s create an example boxplot in Python with matplotlib. We are using Python 3.8.10. Let’s go! ⚡✨

A boxplot or a box and whisker plot is a chart used in exploratory data analysis. It shows the spread, skew and locality of data through its quartiles. Please see the below diagram. This is what we will plot on a graph when we execute our code. But for now, these are the components of a box in a boxplot:

Python Boxplot matplotlib Example
Box Plot Explained
  • max = highest data point excluding outliers
  • upper/third quartile (Q3) = median of higher half of dataset
  • median = middle value of dataset
  • IQR (interquartile range) = distance between upper and lower quartiles
  • lower/first quartile (Q1) = median of lower half of dataset
  • min = lowest data point excluding outliers

Now, let’s write our code:

import matplotlib.pyplot as plt
import numpy as np

# Random data
np.random.seed(26911380)
datasets = [np.random.normal(0, std, size=100) for std in range(1, 4)]
labels = ['x1', 'x2', 'x3']

fig, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(9, 4))

bplot = ax1.boxplot(datasets,
                     vert=True,  
                     patch_artist=True,  
                     labels=labels) 
ax1.set_title('Box Plot Sample')

colors = ['red', 'blue', 'yellow']

for patch, color in zip(bplot['boxes'], colors):
    patch.set_facecolor(color)

for ax in [ax1]:
    ax.yaxis.grid(True)
    ax.set_xlabel('Three separate samples')
    ax.set_ylabel('Observed values')

plt.show()

Let’s explain what is happening here:

  1. First we import the matplotlib library. If it isn’t installed you can install it with the following command: pip install matplotlib.
  2. We import the numpy library. If it isn’t installed you can install with the following command: pip install numpy.
  3. The boxplot is a tool used for statistical analysis so to get some test data, we generate a numpy array of normally distributed values. To do this, we set a random seed with np.random.seed() and then we call the method np.random.normal and pass it 3 values: the loc, the scale and the size. The loc is the center of the distribution, the scale is the standard deviation or spread of the data, and size is number of samples drawn. This step will draw the random samples from a Normal Distribution.
  4. We are generating 3 different datasets which will give us 3 boxes in our boxplot. One for each sample in datasets.
  5. The subplots() method allows us to add additional plots to the figure that will be displayed. In this case we are only adding one subplot.
  6. The ax1.boxplot method will make the box or whisker plot with the given parameters. Find a complete list in the official documentation which you can find HERE.
  7. The we set the color and the labels and then plt.show will actually display the figure to the screen.

If all goes well, when the code executes, you should get the following image displayed to your screen. Notice how it is similar to the above figure. It has all of the structures that we expect:

Python Boxplot matplotlib Example
Python Boxplot matplotlib Example

The little circles outside our box are called outliers, which are data points that differ significantly from the rest of the dataset.

Click HERE for another great matplotlib tutorial on Vector Addition. Thanks for reading and good luck! 👌👌👌

Tags: matplotlib
Previous Post

Python base64 Decode PDF File

Next Post

Python LRU Cache Example

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy