How to make a 2D Histogram/Heatmap of (string) label data in Python?

Viewed 600

I have a large dataset of certain events for the my research industry, organized in a dataframe as follows. Each event has an event type (str), a year of the event (int), event size (int) and an event location (str).

An example dataframe is structured below, with event types 'A', 'B', 'C', or 'D' and event locations 'CA', 'TX', 'NY'.

Event Number Event Type Year Size Location
1 A 2014 1000 CA
2 B 2014 1000 TX
3 C 2014 456 CA
4 C 2014 675 NY
5 B 2014 567 TX
6 A 2014 765 CA
7 C 2014 1000 NY
8 B 2014 675 TX
9 D 2015 3424 NY
10 A 2015 567 TX
11 A 2015 435 CA
12 C 2016 45 CA

Now, I want to plot a heatmap of event type vs year. i.e., a heatmap with year on the x axis, event type on the y-axis, and a heat color representing a count of how many of those types of events happened in that year. The resulting matrix for the above table would look something like this:

Event Type 2014 2015 2016
A 2 2 0
B 3 0 0
C 3 0 1
D 0 1 0

I have looked into using seaborn but I am not sure how to approach this sort of 2D histogram.

How would I go about it if I also wanted to plot a heatmap of location vs event type (2 strings)?

Thanks!

1 Answers

seaborn.histplot can produce a bivariate plot and understand categorical variables, so:

df = pd.read_clipboard()
ax = sns.histplot(data=df, x="Event Type", y="Location", cbar=True)

enter image description here

Related