Python Friday #177: Customise Your Plots in Pandas

The methods to plot a data frame in Pandas (here & here) create us useful graphics. But as with Matplotlib, sometimes they do not fully meet our requirements. Let us find out how we can fix that in Pandas.

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.

 

Name your axes

We can name our X- and Y-axes and set a title for our plot with this code:

The basic plot from Pandas now has a title and labels for the X- and the Y axes:

The basic plot now has a label for the X- and Y axes and a title.

 

Hide the legend

If you only have one line to plot, you can hide the legend:

The generated plot has no legend:

The plot has no legend

 

Show the grid

We can show a grid in our plot:

Depending on the values, the grid can help us to read the data more easily:

The plot with a grid on top of it.

 

Change the line style

For line plots we can change the style of the line and the colour:

This uses a dashed green line for the plot:

Instead of a solid line we get a dashed one in green.

 

Change the plot size

We can use the figsize parameter to change the size of our plot:

This changes the size of our plot to 3 x 3 inches:

Our plot is a lot smaller than usual.

 

Style your plots

We can use the Matplotlib styles for our Pandas plots:

This renders our plot with the style “fivethirtyeight“:

The plot uses the style fivethirtyeight instead of the default one.

 

Use the underlying Matplotlib objects directly

If you know how to do the customisation in Matplotlib but not in Pandas, you can always leave the abstraction behind and work directly on the Matplotlib objects:

This allows us to customise all aspects of the plots as we could do it directly in Matplotlib:

The tics of the X axis now show all months with a 90-degree rotation.

 

Change the colours in the box plot

The box plot allows us to style the different parts of the plot:

This adds a lot more colour to the box plot:

The different parts of the box plot are now in different colours.

 

Show the values in a pie chart

If we want to see the percentages in the wedge of a pie chart, we can use this code:

This shows us the percentage value for each part:

The pie chart shows us the percentages for each wedge.

If we want to show the effective values from the data, we need to calculate that value from the percentage and the sum of all values:

This gives us the same values as in the data frame:

The pie chart now shows us the values instead of the percentages.

 

Next

We now can plot our data frames and change their appearance to our needs. But what happens if we have messy data? Next week we clean-up a data source to use it in Pandas.

1 thought on “Python Friday #177: Customise Your Plots in Pandas”

Leave a Comment

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