Python Friday #176: Visualise Data in Pandas With Hist() & Boxplot()

Plotting with Pandas works without much effort. Today we look at the two dedicated methods hist() and boxplot() directly on the data frame.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Box plot

For the box plots we reuse the data frame with the temperatures from the last post. If we use df.plot.box() on the whole data frame, we get a box for each city:

The box plot shows us three bars, one for each city.

We can also use the method df.boxplot() directly on the data frame to create the box plot:

It gives us the same representation, but it shows the grid by default:

The box plot with three bars for the cities, but this time with a visible grid line.

We can style the output of the df.boxplot() method, but I prefer the df.plot.box() approach.

 

Histograms

For the histogram we need a new data frame with test scores for 3 candidates:

If we filter for the column “a”, the histogram shows us an expected plot:

The values for candidate a get counted and displayed as bars of a histogram

To get a histogram for each candidate, we may try this call without a filter:

Unfortunately, that creates one single histogram over the whole data frame:

The data of the 3 candidates is mixed together and impossible to separate.

To get the expected result, we need to df.hist() method directly in the data frame:

The call to the Matplotlib specific feature for the layout is only needed to get the 3 histograms next to each other:

We now have 3 separate histograms next to each other.

 

Next

The two methods hist() and boxplot() directly on the data frame are a little bit different compared to the other plot() methods. Nonetheless, we can use those methods to create the plots we want. Next week we explore the options to style and customise our plots in Pandas.

3 thoughts on “Python Friday #176: Visualise Data in Pandas With Hist() & Boxplot()”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.