Home > Blockchain >  How to plot the position of occurrence in python data frame
How to plot the position of occurrence in python data frame

Time:04-26

For example I have a data frame like the following:

   A  B  C
0  1  1  1
1  1  1  0
2  1  1  0
3  1  0  1
4  1  0  1
5  1  0  0
6  0  1  0
7  0  1  1
8  0  1  0
9  0  1  1

How can I plot a graph like the following that indicates the index position of column A, B, and C that had a 1? plot of the index position

The top bar shows column A, the middle bar shows column B, and the bottom bar shows column C. The x-axis are the index. For each bar, blue means that there is a 1 at this index for this column, and grey means the opposite.

CodePudding user response:

Assuming your data in df, you can call plt.imshow on the transposed dataframe:

import matplotlib.pyplot as plt
plt.imshow(df.T, cmap='Blues')

enter image description here

edit: For datasets with rows >> columns or columns >> rows the scaling can be messed up. This can be changed by changing the aspect of the figure. I am using 10 here, but you should probably play around with some values (maybe 0.1 to 100)

plt.imshow(df.T, cmap='Blues')
plt.gca().set_aspect(10)

enter image description here

  • Related