0

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,

enter image description here

  • Does your dataframe contain values for every index in the grid? Is the column `Result` of type `string` or `boolean`? Your image has only 10 rows, your example dataframe has `Row` values for index `12`. – Michael Szczesny Dec 13 '20 at 15:00
  • dataframe contains values for each index, results are in string, image is just for reference , the actual grid size is 12 x 8 @MichaelSzczesny –  Dec 13 '20 at 15:05

1 Answers1

0

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()

example plot

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']).

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • Thanks for the answer! But what can I do if I got the 3rd values? say I have multiple values (rather than true or false) and I want to plot them on the grid... – Xu Shan May 10 '22 at 09:51
  • You could map the values to numbers and then use a ListedColormap with a color for each value. – JohanC May 10 '22 at 11:22