Tobias Tobias -4 years ago 108
Python Question

Python - Pick_Event for pcolor get pandas column and index value

I am trying to to create a pick_event for pcolor which is working fine so far. however, I would like to get the column and index name of the underlying pandas DataFrame.
With event.ind I just get one value which seems to be counted with ignoring nan values.

Eventually I would like to use the column and index name to return a value from another pandas DataFrame with the same index and column values.

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

class colormap:
def __init__(self):
pass

def create(self):
fig, ax = plt.subplots()
data = pd.DataFrame(np.arange(0,12).reshape(3,4), index=['a', 'b', 'c'], columns=['A', 'B', 'C', 'D'], dtype=float)
data.set_value('a', 'B', np.nan)
data = np.ma.masked_where(np.isnan(data), data)

ax.pcolor(data, edgecolors='k', linewidths=0.2, cmap='RdBu', picker=1)
fig.canvas.mpl_connect('pick_event', self.onpick)
plt.show()

def onpick(self, event):
self.event = event
self.thisline = event.artist
ind = event.ind
print(ind)

if __name__ == '__main__':
self = colormap()
self.create()

Answer Source

One option is to work with a non masked array. This will throw a warning, but still works, if you set the colorlimits in pcolor using vmin and vmax. In order for the nan value to become transparent one needs to set the colormap.set_under(color) to a transparent color.

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

class colormap:
    def __init__(self):
        pass

    def create(self):
        fig, ax = plt.subplots()
        self.data = pd.DataFrame(np.arange(0,12).reshape(3,4), index=['a', 'b', 'c'], 
                            columns=['A', 'B', 'C', 'D'], dtype=float)
        self.data.set_value('a', 'B', np.nan)
        #data = np.ma.masked_where(np.isnan(data), data)
        cmap = plt.cm.RdBu
        cmap.set_under((0,0,0,0))
        ax.pcolor(self.data, edgecolors='k', linewidths=0.2, cmap=cmap, picker=1, 
                  vmin=0, vmax=11)
        fig.canvas.mpl_connect('pick_event', self.onpick)
        plt.show()

    def onpick(self, event):
        self.event = event
        self.thisline = event.artist
        ind = event.ind
        x,y = np.unravel_index(ind, self.data.shape)
        x,y = x[0],y[0]
        print (x,y, self.data.iloc[x,y])

if __name__ == '__main__':
    self = colormap()
    self.create()

In this way the return (n,m, self.data.iloc[n,m]) is the (row, column, data[row,column]).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download