LoLa
LoLa

Reputation: 1320

How to plot a DataFrame with binary values as a color matrix?

I have a DataFrame that resembles the following:

Name V1 V2 V3
A    1  0  0
B    1  0  1
C    1  1  0

etc.

I would like to visualize it as a 2-d matrix with labeled rows and columns and with cells colored based on whether the value is 1 or 0.

In other words, I would like to do something like this: Conditional coloring of a binary data frame in R

but in Python.

Any help is appreciated!

Upvotes: 2

Views: 5938

Answers (2)

Anton vBR
Anton vBR

Reputation: 18916

Could plot them as an image with various cmap alternatives: https://matplotlib.org/examples/color/colormaps_reference.html

But from here you would need more formatting...

import matplotlib.pyplot as plt
plt.imshow(df.values, interpolation="nearest", cmap='Blues')
plt.show()

enter image description here

Upvotes: 1

cs95
cs95

Reputation: 402813

Fleshing out Wen's comment into an answer - use seaborn.heatmap:

import matplotlib.pyplot as plt
import seaborn as sns

sns.set()

df = df.set_index('Name')
df

      V1  V2  V3
Name            
A      1   0   0
B      1   0   1
C      1   1   0
sns.heatmap(df)
plt.show()

enter image description here

Upvotes: 4

Related Questions