Combo Charts with Seaborn and Python | by Conner Leavitt | Towards Data Science

The libraries, code, and visuals will be down below but first I wanted to offer a brief introduction as to why I decided to share this with everyone in this community. If you just want to skip down to the tutorial just skip the intro.
While at work a few of my colleagues who use Excel as their primary tool like to try and find ways in which excel is a better tool than Python. Due to the fact that they are unfamiliar with the capabilities of Python, they tend to inquisitively ask if Python can handle the same tasks as Excel. For example, they ask questions like, “can Python perform a task similar to a VLOOKUP?” or “can python build pivot tables?” and my answer is always “yes”. The questions are always asked with a sense of humor as they have grown used to me turning around in my chair with a big grin on my face as I can’t wait to utter the three-letter word “yes”. My colleagues and friends have grown so tired of my response that I now host a one-hour python class once a week. During one of the classes I was teaching my coworkers how to create powerful visuals with seaborn, one person asked, “Can Python build combo charts?” I was silent and my friends all lite up as they looked up to my blank stare. They began to cheer and declare they have finally found something that Excel can do that python cannot. We all had a good laugh and once things settled down I explained Python can create combo charts, however, I have never built one so I do not know-how. So my makeshift class challenged me to figure out how to create combo charts and prove that Python can do everything excel can. So I did.
I want to take a second to clarify that I do not think Excel in a bad tool, but I am a strong advocate for learning python. So if you are wanting to make the jump from Excel to Python I encourage you to do so!
Once I figured out how to build a combo chart I thought to myself.....”I need to share this knowledge”. The topic of this article is going to be how to build a combo chart in python with seaborn and matplotlib. I may be the only person in the Python community that did not know how to create combo charts, but if you were like me and was ignorant of Python’s capabilities of building these types of visuals this article is for you!
Below are the libraries we are going to need to accomplish this task. If you do not already have these libraries you can use pip install to obtain them.
import pandas as pdimport matplotlibimport matplotlib.pyplot as pltimport seaborn as sns
Before we can make visuals we need data. Let’s create our own data set with pandas. I am going to create data rather than import a data set because I want data that will be ready to visualize
#create list of monthsMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June',          'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']#create list for made up average temperaturesAvg_Temp = [35, 45, 55, 65, 75, 85, 95, 100, 85, 65, 45, 35]#create list for made up average percipitation %Avg_Percipitation_Perc = [.90, .75, .55, .10, .35, .05, .05, .08, .20, .45, .65, .80]#assign lists to a valuedata = {'Month': Month, 'Avg_Temp': Avg_Temp, 'Avg_Percipitation_Perc': Avg_Percipitation_Perc}#convert dictionary to a dataframedf = pd.DataFrame(data)#Print out all rowsdf[:12]
Now that we have some data we can create visuals. Before we make the combo chart let’s create two separate visuals that we would want to turn into a combo chart. So, with our data let’s make a bar plot for average temperature by month and a line plot by average precipitation percentage.
#create bar plot for average temps by monthplt.title('Average Temperature by Month')sns.barplot(x='Month', y='Avg_Temp', data=df, palette='summer')
# create line plot for average percipitation levelsplt.title('Average Percipitation Percentage by Month')sns.lineplot(x='Month', y='Avg_Percipitation_Perc', data=df, sort=False)
Perfect. We have two unique plots that can be condensed into one plot and still make sense. So, let’s work on figuring out how to get that done.
The trick to making the combo chart is to use two different axes that share the same x-axis. This is possible through the twinx() method in matplotlib. This generates two separate y-axes that share the same x-axis.
There is another method, twiny(), that does the exact same thing but the y-axis is shared the x-axes are unique.
With this newly discovered method let’s try and combine our two charts.
In order to do this we will still need to code out the two plots, we will just need to be sure that we state that we want the two plots to share in one axis and be unique in the other.
#Create combo chartfig, ax1 = plt.subplots(figsize=(10,6))color = 'tab:green'#bar plot creationax1.set_title('Average Percipitation Percentage by Month', fontsize=16)ax1.set_xlabel('Month', fontsize=16)ax1.set_ylabel('Avg Temp', fontsize=16)ax1 = sns.barplot(x='Month', y='Avg_Temp', data = df, palette='summer')ax1.tick_params(axis='y')#specify we want to share the same x-axisax2 = ax1.twinx()color = 'tab:red'#line plot creationax2.set_ylabel('Avg Percipitation %', fontsize=16)ax2 = sns.lineplot(x='Month', y='Avg_Percipitation_Perc', data = df, sort=False, color=color)ax2.tick_params(axis='y', color=color)#show plotplt.show()
It looks good right! Well, not quite. What axis corresponds with which plot? We can clear up some of this confusion by adding another keyword argument in the set_ylabel() method. Let’s add that argument below and see if we cannot make this plot clearer.
fig, ax1 = plt.subplots(figsize=(10,6))color = 'tab:green'ax1.set_title('Average Percipitation Percentage by Month', fontsize=16)ax1.set_xlabel('Month', fontsize=16)ax1.set_ylabel('Avg Temp', fontsize=16, color=color)ax2 = sns.barplot(x='Month', y='Avg_Temp', data = df, palette='summer')ax1.tick_params(axis='y')ax2 = ax1.twinx()color = 'tab:red'ax2.set_ylabel('Avg Percipitation %', fontsize=16, color=color)ax2 = sns.lineplot(x='Month', y='Avg_Percipitation_Perc', data = df, sort=False, color=color)ax2.tick_params(axis='y', color=color)plt.show()
There you have it a combo chart in python. I know some people would argue that combo charts aren’t a great way of visualizing data, but sometimes your boss wants two pieces of information on plot and sometimes it makes sense to combine plots. I am only here to show that it can be done and how it can be done.
In short, there is always something to learn and practice in python whether it is a big task or a small application. I encourage everyone to continually learn and improve their python by questioning what you know and what is possible!