Categories
design media

Combo Charts with Seaborn and Python

Masking two plots to make one chart

Conner Leavitt

http://www.terrystickels.com/math-art/images/synchronized_curves_std.jpg

Intro

The libraries, code, and visuals shall be down under however first I sought after to provide a short lived advent as to why I made up our minds to percentage this with everybody on this neighborhood. In case you simply wish to skip all the way down to the academic simply skip the intro.

Whilst at paintings a couple of of my colleagues who use Excel as their number one device like to check out and to find tactics by which excel is a greater device than Python. Because of the truth that they’re unfamiliar with the features of Python, they generally tend to inquisitively ask if Python can maintain the similar duties as Excel. For instance, they ask questions like, “can Python carry out a role very similar to a VLOOKUP?” or “can python construct pivot tables?” and my solution is at all times “sure”. The questions are at all times requested with a humorousness as they’ve grown used to me turning round in my chair with a large grin on my face as I will be able to’t wait to utter the three-letter phrase “sure”. My colleagues and buddies have grown so bored with my reaction that I now host a one-hour python elegance as soon as per week. Right through one of the categories I used to be educating my coworkers learn how to create robust visuals with seaborn, one particular person requested, “Can Python construct combo charts?” I used to be silent and my buddies all lite up as they appeared as much as my clean stare. They started to cheer and claim they’ve after all discovered one thing that Excel can do this python can not. All of us had a excellent snort and as soon as issues settled down I defined Python can create combo charts, alternatively, I’ve by no means constructed one so I don’t technology. So my makeshift elegance challenged me to determine learn how to create combo charts and turn out that Python can do the whole lot excel can. So I did.

I wish to take a 2nd to explain that I don’t suppose Excel in a nasty device, however I’m a robust recommend for finding out python. So in case you are in need of to make the bounce from Excel to Python I beg you to take action!

After I discovered learn how to construct a combo chart I believed to myself…..”I want to percentage this data”. The subject of this article will be learn how to construct a combo chart in python with seaborn and matplotlib. I could also be the one particular person within the Python neighborhood that didn’t know the way to create combo charts, however should you have been like me and used to be unaware of Python’s features of creating a majority of these visuals this newsletter is for you!

Dependencies

Beneath are the libraries we’re going to want to accomplish this activity. If you don’t have already got those libraries you’ll use pip set up to procure them.

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns

Information

Sooner than we will make visuals we want information. Let’s create our personal information set with pandas. I’m going to create information reasonably than import a knowledge set as a result of I need information that shall be able to visualise

#create listing of months
Month = ['Jan', 'Feb', 'Mar', 'Apr', 'Would possibly', 'June',
'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
#create listing for made up moderate temperatures
Avg_Temp = [35, 45, 55, 65, 75, 85, 95, 100, 85, 65, 45, 35]
#create listing for made up moderate percipitation %
Avg_Percipitation_Perc = [.90, .75, .55, .10, .35, .05, .05, .08, .20, .45, .65, .80]
#assign lists to a worth
information = {'Month': Month, 'Avg_Temp': Avg_Temp, 'Avg_Percipitation_Perc': Avg_Percipitation_Perc}
#convert dictionary to a dataframe
df = pd.DataFrame(information)
#Print out all rows
df[:12]

Information set

Plotting

Now that we’ve got some information we will create visuals. Sooner than we make the mix chart let’s create two separate visuals that we’d wish to transform a combo chart. So, with our information let’s make a bar plot for moderate temperature by way of month and a line plot by way of moderate precipitation proportion.

#create bar plot for moderate temps by way of month
plt.name('Reasonable Temperature by way of Month')
sns.barplot(x='Month', y='Avg_Temp', information=df, palette='summer season')

Bar plot

# create line plot for moderate percipitation ranges
plt.name('Reasonable Percipitation Share by way of Month')
sns.lineplot(x='Month', y='Avg_Percipitation_Perc', information=df, kind=False)

Easiest. We now have two distinctive plots that may be condensed into one plot and nonetheless make sense. So, let’s paintings on working out learn how to get that achieved.

The Magic Approach

The trick to creating the mix chart is to make use of two other axes that percentage the similar x-axis. That is imaginable throughout the twinx() means in matplotlib. This generates two separate y-axes that percentage the similar x-axis.

There may be any other means, twiny(), that does the very same factor however the y-axis is shared the x-axes are distinctive.

With this newly found out means let’s attempt to mix our two charts.

With the intention to do that we will be able to nonetheless want to code out the two plots, we will be able to simply want to ensure that we state that we would like the two plots to percentage in one axis and be distinctive within the different.

#Create combo chart
fig, ax1 = plt.subplots(figsize=(10,6))
colour = 'tab:inexperienced'
#bar plot introduction
ax1.set_title('Reasonable Percipitation Share by way of Month', fontsize=16)
ax1.set_xlabel('Month', fontsize=16)
ax1.set_ylabel('Avg Temp', fontsize=16)
ax1 = sns.barplot(x='Month', y='Avg_Temp', information = df, palette='summer season')
ax1.tick_params(axis='y')
#specify we wish to percentage the similar x-axis
ax2 = ax1.twinx()
colour = 'tab:purple'
#line plot introduction
ax2.set_ylabel('Avg Percipitation %', fontsize=16)
ax2 = sns.lineplot(x='Month', y='Avg_Percipitation_Perc', information = df, kind=False, colour=colour)
ax2.tick_params(axis='y', colour=colour)
#display plot
plt.display()

It appears excellent proper! Smartly, no longer somewhat. What axis corresponds with which plot? We will be able to transparent up a few of this confusion by way of including any other key phrase argument within the set_ylabel() means. Let’s upload that argument under and spot if we can not make this plot clearer.

fig, ax1 = plt.subplots(figsize=(10,6))
colour = 'tab:inexperienced'
ax1.set_title('Reasonable Percipitation Share by way of Month', fontsize=16)
ax1.set_xlabel('Month', fontsize=16)
ax1.set_ylabel('Avg Temp', fontsize=16, colour=colour)
ax2 = sns.barplot(x='Month', y='Avg_Temp', information = df, palette='summer season')
ax1.tick_params(axis='y')
ax2 = ax1.twinx()
colour = 'tab:purple'
ax2.set_ylabel('Avg Percipitation %', fontsize=16, colour=colour)
ax2 = sns.lineplot(x='Month', y='Avg_Percipitation_Perc', information = df, kind=False, colour=colour)
ax2.tick_params(axis='y', colour=colour)
plt.display()

There you’ve gotten it a combo chart in python. I do know some folks would argue that combo charts aren’t an effective way of visualizing information, however from time to time your boss needs two items of knowledge on plot and from time to time it is sensible to mix plots. I’m simplest right here to turn that it may be achieved and the way it may be achieved.

Conclusion

Briefly, there’s at all times one thing to be told and observe in python whether or not this is a large activity or a small utility. I beg everybody to repeatedly be told and toughen their python by way of wondering what you recognize and what’s imaginable!