Visualize Categorical Relationships With Catscatter | by Myriam | Towards Data Science

If you ever needed a way to plot categorial features showing its relationships, I’ve built this resource for you. A catscatter function built over matplotlib.pyplot object and using pandas to visualize relationships between your categorial variables as if it were a scatter plot. (I know, there’re no correlations here, but it looks like it and its built on a scatter plot, right?).
github.com
I work as a Data Analyst using a bit of Data Science and a lot of Data Visualization. Last December a coworker gave me for Christmas the book “Knowledge is Beautiful” which I loved. Its Data Visualizations are amazing and really complex. I like to read it when I want to get inspired.
At the same time, I work for a VC fund, where frameworks and relationships are really important. Showing relationships between categorical variables is not always an easy thing due to their “string” nature.
These two situations motivated me to create and use a catscatter function. This function is based in scatter plots relationships but uses categorical variables in a beautiful and simple way. Actually, the visualization is closer to an “adjacency matrix” than a “scatter plot”: it means that we are not interested in where the markers are to find correlations but on which categories are connected to each other, or which ones are more connected to something than to something else. They can be seen as a kind of “graph” relationships. For that purpose it was important to not only plot the markers in the intersections between features but to draw horizontal and vertical lines in the background to follow easily the connections.
The function is built for Python over Matplotlib and Pandas. It has the following inputs:
df: pandas DataFrame, required. It needs at least two columns with the categorical variables you want to relate, and the value of both (if it’s just an adjacent matrix write a column with )
colx: string, required. The name of the column to display horizontally.
coly: string, required. The name of the column to display vertically.
cols: string, required. The name of the column with the value between the two variables.
color: list, optional. Colors to display in the visualization, the length can be two or three. The two first are the colors for the lines in the matrix, the last one the font color and markers color. default [‘grey’,’black’]
ratio: int or float, optional. A ratio for controlling the relative size of the markers. default 10
font: string, optional. The font for the ticks on the matrix. default ‘Helvetica’
save: bool, optional. True for saving as an image in the same path as the code. default False
save_name: string, optional. The name used for saving the image (then the code ads .png) default: “Default”
There’s no output. The object is not closed so it can be initiated or changed by the user before and after.
Imagine you invite some of your friends to have dinner at home. You can build a catscatter to see everyone favorite food and buy what’s more suitable for all of them. You need a DataFrame containing the relationships between your friends and food. For example, you know that Ignacio loves Hamburguers but also likes Pizza, so you built a relationship between “Ignacio” and “Hamburguer” with a grade “5” and a relationship between “Ignacio” and “Pizza” of grade “3”. You do the same for everything you know about your friends and plot a catscatter.
import pandas as pdimport matplotlib as pltfrom catscatter import catscatter# example data framedata=pd.DataFrame({‘friend’:[‘Peter’,’Marc’,’Ignacio’,’Marta’,’Marta’,’Ignacio’,’Maria’,’Pedro’,’Bea’,’Pedro’], ‘favorite_food’:[‘Salmon’,’Chocolate’,’Hamburguer’,’Pizza’,’Apples’,’Pizza’,’Pizza’,’Hamburguer’,’Salmon’,’Banana’], ‘favorite_grade’:[1,5,5,3,2,3,4,4,3,1]})#plot itcatscatter(data,’friend’,’favorite_food’,’favorite_grade’)plt.show()
Output:
Here you can see that Pizza is the most liked food, but if you are inviting Bea and Peter maybe ordering Salmon Tataki is the best option. Don’t waste your time buying fruit. For Marc, I’m sure you’ve only had desserts with him, you should invite him to a dinner to gather more data!
This example is the same than the one before but bigger and more colorful.
import pandas as pdimport matplotlib as pltfrom catscatter import catscatter# example dataframedata=pd.DataFrame({‘friend’:[‘Peter’,’Marc’,’Ignacio’,’Marta’,’Marta’,’Ignacio’,’Maria’,’Pedro’,’Bea’,’Pedro’], ‘favorite_food’:[‘Salmon’,’Chocolate’,’Hamburguer’,’Pizza’,’Apples’,’Pizza’,’Pizza’,’Hamburguer’,’Salmon’,’Banana’], ‘favorite_grade’:[1,5,5,3,2,3,4,4,3,1]})colors=[‘green’,’grey’,’orange’]# create the plotplt.figure(figsize=(8,8))catscatter(data,’friend’,’favorite_food’,’favorite_grade’,color=colors,ratio=100)plt.xticks(fontsize=14)plt.yticks(fontsize=14)plt.show()
Output:
At my office we wanted to know which EU Seed Investors are more active in which Industries. I gather information about all the seed rounds between 2015 and 2019 in Europe and prepare a dataset with the number of deals each Investor made by Industry (if no deals there’s no row). The number of deals is how strong or weak is the relationship between the Industry and the Investor.
import pandas as pdimport matplotlib.pyplot as pltfrom catscatter import catscatter# read the dataframedf=pd.read_csv(“top-european-investors-seed-rounds-15–19.csv”)df
Output:
kcolors=[‘#F73972’,’#F2B3C6',’#144962']# create the plotplt.figure(figsize=(50,20))catscatter(df,’Investor’,’Company Industry’,’Announced Date’,color=kcolors, ratio=20)plt.xticks(fontsize=20)plt.yticks(fontsize=20)plt.show()
Output:
We had 700 Investors and 600 Industries, but for this visualization I only leave the top 100 Investors and top 50 Industries more active. At my office we created two posters that you can find here and here.
In the one displayed here, you can see that “High-Tech Grunderfonds” made deals in almost all of the top sectors, but with more focus on “Information Technology” and “Software”. Also “Innogest Capital” and “Inbox Capital” have made nearly the same number of deals, but “Inbox Capital” is generalist and “Innogest Capital” focused only on “Ecommerce” and “Fashion”. We can see also that “Advertising” is not really common but “Software” is, and there’re Investors that focus on “Medical” but not on “Travel”
I can’t share the df used for the last one, but I hope it helps seeing the potential of my little piece of code at a bigger scale.
If you want to try catscatter here’s the code for you! 👇
github.com
What do you think? Do you find it useful? What other ways do you have to plot relations between categorical features? Let me know in the comments section!
If you use it I would love to know it too 🤗