5 Easy Ways of Customizing Pandas Plots and Charts | by Alan Jones | Towards Data Science

Perhaps you are a data journalist putting a new story together, or a data scientist preparing a paper or presentation. You’ve got a nice set of charts that are looking good but a bit of tweaking would be helpful. Maybe you want to give them all titles. Maybe some would be improved with a grid, or the ticks are in the wrong places or too small to easily read.
You know how to produce line plots, bar charts, scatter diagrams, and so on but are not an expert in all of the ins and outs of the Pandas plot function (if not see the link below).
medium.com
You don’t have to stick with what you are given. There are quite a lot of parameters that allow you to change various aspects of your diagrams. You can change labels, add grids, change colors and so on.
Using the underlying matplotlib library you can change just about every aspect of what your plots look like and it can get complicated. However, we are going to look at some of the easier things we can do just with Pandas.
Before we start you’ll need to import the appropriate libraries and get some data.
Let’s start by importing all of the libraries that you’ll need to run the examples
# The first line is only required if you are using a Jupyter Notebook %matplotlib inline import numpy as npimport pandas as pdimport matplotlib.pyplot as plt
This is all pretty standard stuff which should be familiar from my previous article. One thing to note though is the first line — if, like me, you are using a Jupyter Notebook then you may need to include this. If you are using a normal Python program, or the Python console, then you should not include it.
You need some data to work with, so we’ll use the same data set as previously: weather data from London, UK, for 2008.
Load the data like this:
weather = pd.read_csv(‘https://raw.githubusercontent.com/alanjones2/dataviz/master/london2018.csv')print(weather[:2])Year Month Tmax Tmin Rain Sun 0 2018 1 9.7 3.8 58.0 46.5 1 2018 2 6.7 0.6 29.0 92.0
The print statement prints out the first couple of lines of the table, representing January and February. You can see that there are four pieces of data (apart from the year and month), Tmax is the maximum temperature for that month, Tmin is the minimum temperature, Rain is the rainfall in millimeters and Sun is the total hours of sunshine for the month.
So let’s just draw a simple plot of how the maximum temperature changed over the year
weather.plot(x=’Month’, y=’Tmax’)plt.show()
This is the default chart and it is quite acceptable. But we can change a few things to make it more so.
The first thing that you might want to do is change the size. To do this we add the figsize parameter and give it the sizes of x, and y (in inches). The values are given a a tuple, as below.
To change the color we set the color parameter. The easiest way to do this is with a string that represents a valid web color such as ‘Red’, ‘Black’ or ‘Teal’. (Note: you can find a list of web colors in Wikipedia.)
weather.plot(x='Month', y='Tmax', figsize=(8,5), color='Red')plt.show()
It’s very likely that for and article, paper or presentation, you will want to set a title for your chart. As you’ve probably gathered, much of this is knowing what the correct parameters are and setting them properly. The parameter to set a title is title. Of course! Here’s the code:
weather.plot(x=’Month’, y=’Tmax’, title=”Maximum temperatures”)plt.show()
While the default charts are fine, sometimes you want your audience to more easily see what certain values in your chart. Drawing gridlines on your plot can help.
To draw the grid, simply set the grid parameter to True. Pandas defaults to False.
weather.plot(x=’Month’, y=’Tmax’, grid=True)plt.show()
The legend is given the name of the column that represents the y axis. If this is not a acceptably descriptive name, you can change it. Or, indeed, you can eliminate it altogether!
If we want to remove it we set the parameter legend to False. If we want to change the label we incorporate the label parameter and set it to the string that we want displayed.
weather.plot(x=’Month’, y=’Tmax’, legend=False)plt.show()
weather.plot(x=’Month’, y=’Tmax’, label=’Max Temp’)plt.show()
Ticks are the divisions on the x and y axes. You can see that on our charts they are labelled from 10 to 25 on the y axis and 2 to 12 on the y axis. Given that the bottom set are supposed to represent the months, it would be better if they went from 1 to 12. We can set the tick labels with tuples. If we want to display all twelve months we would set the parameter xticks to (1,2,3,4,5,6,7,8,9,10,11,12). You can do a similar thing with the yticks parameter. Take a look at this code:
weather.plot(x=’Month’, y=’Tmax’, xticks=range(1,13), yticks=(0,10,20,30))plt.show()
As you can see I’ve set both sets of ticks explicitly. The y ticks now start at 0 and go up in tens to 30, and the x ticks show every month. But I’ve been a bit sneaky here, rather than use the tuple I showed you, above, I’ve used the Python range function to generate a list from 1 to 12 (less typing!).
If you wanted to remove the ticks altogether, it would be a simple matter to set either parameter to an empty tuple, e.g. xticks=().
weather.plot(x=’Month’, y=’Tmax’, xticks=())plt.show()
I you want to emphasize the ticks even more you can change the font size. In the example below, you can see how.
plot = weather.plot(x=’Month’, y=’Tmax’, xticks=range(1,13), fontsize=18)plt.show()
I mean your code could get messy. What if you wanted to set the ticks, a title, labels, a grid and so on. First, the line of code to do the plot would be very long and, second, if you have several plots to make you find yourself repeating it.
Here’s a solution.
Assume that you want all of you plots to look the same. What you do is define a dictionary of all of the parameters that you want to apply to all of your charts, like this:
plot_kwargs={‘xticks’:range(1,13), ‘yticks’:(0,10,20,30), ‘grid’:True, ‘fontsize’:12}
then instead of typing in all of the parameters explicitly, you can take advantage of Python’s ** operator which will expand a dictionary into a list of keyword arguments. I’ve called the variable plot_kwargs as kwargs is the conventional name given to a variable containing keyword parameters (which is what these are).
Use them like this:
weather.plot(y=’Tmax’,x=’Month’, **plot_kwargs)plt.show()
Now, you can use the same dictionary for other plots, too, for example:
weather.plot.scatter(y=’Tmax’,x=’Month’, legend=True, label=”Min Temperature”, **plot_kwargs)plt.show()
Here, I’ve used the plot_kwargs parameter to set the default parameters but explicitly set the ones for the individual plot.
Well, no. It isn’t really. There is a lot you can do to customize your plots more both with Pandas and matplotlib. You can also make changes when you save the plots to a file. There is just far too much to cover in a single article.
Thanks, for getting to the end of the article, I hope you have found it useful.
A quick postscript about the format. All of the code is very short but some lines are little long and wrap around — so I’ve put a blank line after each line so you can see what is supposed to be on one line. The only exception in the dictionary assignment towards the end of the article, which is fine the way it looks.