Sepehr
Sepehr

Reputation: 452

Plotting boolean dataframes with a condition

I have two dataframes such as the following:

test1 = pd.DataFrame({'A':[False, False, False, True], 'B':[False, False, True, False], 'C':[True, False, True, False]})

which produces:

      A       B      C
0   False   False   True
1   False   False   False
2   False   True    True
3   True    False   False

and

test2 = pd.DataFrame({'A':[False, False, False, False], 'B':[True, False, True, False], 'C':[False, False, False, False]})

which produces:

      A      B        C
0   False   True    False
1   False   False   False
2   False   True    False
3   False   False   False

I want to plot these dataframes in a single plot in such a way that the y axis is the column names and x axis is the index. I would like to have a yellow dot wherever the corresponding value is True. If the corresponding value is True in both dataframes then I would like to have a red dot.

Any help is highly appreciated.

Upvotes: 1

Views: 2979

Answers (1)

takoika
takoika

Reputation: 363

I make a graph: x-axis indicate a column index (A, B or C), y-axis indicate a row index. Is that what you want to do?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

test1 = pd.DataFrame({'A':[False, False, False, True], 'B':[False, False, True, False], 'C':[True, False, True, False]})
test2 = pd.DataFrame({'A':[False, False, False, False], 'B':[True, False, True, False], 'C':[False, False, False, False]})


# Make a matrix whose elements are 0 if both are True, 1 if neither True, else 2.
mat = np.vectorize( lambda a,b: 0 if a and b else 1 if a or b else 2)(test1,test2) 

y,x = np.where(mat==0)
plt.plot(x, y, 'ro')
y,x = np.where(mat==1)
plt.plot(x, y, 'yo')

xlabels = test1.columns

plt.ylim(-1,len(test1.index))
plt.xlim(-1,len(xlabels))

plt.xticks(range(len(xlabels)), xlabels)

plt.show()

Upvotes: 2

Related Questions