I have a dataset containing row and column values and corresponding True or False, such as
Sr. Row Col Result
1 2 4 true
2 12 5 false
3 5 4 false
And I would like to plot it as bellow,
I have a dataset containing row and column values and corresponding True or False, such as
Sr. Row Col Result
1 2 4 true
2 12 5 false
3 5 4 false
And I would like to plot it as bellow,
You can grab the positive indices via df[df['Result'] == 'true']
. As your indices seem to start with 1, subtract 1 for the rows and 1 for the columns. Use these indices to fill in a matrix. Then use imshow
to display that matrix.
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
import pandas as pd
df = pd.DataFrame({'Row': [2, 12, 5, 1, 12, 12],
'Col': [4, 5, 4, 1, 1, 8],
'Result': ['true', 'false', 'false', 'true', 'true', 'true']})
positive_indices = df[df['Result'] == 'true'][['Row', 'Col']].to_numpy() - np.array([1, 1])
matrix = np.zeros((12, 8), dtype=bool)
matrix[positive_indices[:, 0], positive_indices[:, 1]] = True
fig, ax = plt.subplots()
ax.imshow(matrix, extent=[.5, 8.5, .5, 12.5], cmap='bwr_r', origin='lower')
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(1))
plt.show()
PS: To have the first row at the top, reverse the y-limits in the extent and use origin='upper'
(the default):
ax.imshow(matrix, extent=[.5, 8.5, 12.5, .5], cmap='bwr_r', origin='upper')
Colormap cmap='bwr'
would color the 'true'
cells red. A ListedColormap
provides even more control over the color, e.g. cmap=matplotlib.colors.ListedColormap(['Crimson', 'DeepSkyBlue'])
.