Referring to plot bars in MatPlotLib

Viewed 50

I have the below code and i'm trying to figure out how to change the colours of the bars based on a pick event. When i click a bar it runs onpick(), compares the height to a mean and makes a colour list that i then pass to the bars in the ax.bars line

I can pull out the clicked artist (a patches.rectangle) with the variable y, I can then find the properties of it with plt.getp(y) which tells me what the facecolour is. If I try plt.setp(y, fc='k') I can then see that the facecolour property of y has changed but the plot doesn't change. Any help in how I can refer to the rectangle drawn and update its properties?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import scipy.stats as st
import statsmodels.stats.api as sms

%matplotlib notebook

np.random.seed(12345)

df = pd.DataFrame([np.random.normal(32000,200000,3650), 
                   np.random.normal(43000,100000,3650), 
                   np.random.normal(43500,140000,3650), 
                   np.random.normal(48000,70000,3650)], 
                  index=[1992,1993,1994,1995])
df = df.T
fig = plt.figure()
ax = fig.add_subplot(111)
text=ax.text(0,45000, 'asdf',va='baseline', ha='left')
means = []
yerrs = []
for x in df.columns:
    means.append(df[x].mean())
    yerrs.append((df[x].mean()-sms.DescrStatsW(df[x]).tconfint_mean()[0]))
colours=['r','b','k','m']
ax.bar(range(len(means)),means,yerr=yerrs, capsize=3, picker=True, label=df.index)
ax.set_xticklabels([None,'1992','1993','1994','1995'])
ax.locator_params('x',nbins=8)
def onpick(event):
    global x
    x = float(event.artist.get_height())
    global y
    y = event.artist
    global colours
    colours=[]
    global heights
    heights=[]
    for value in means:
        heights.append(value)
        if x == value:
            colours.append('k')
        if x > value:
            colours.append('r')
        if x < value:
            colours.append('b')
    ax.cla()
    global bars
    ax.bar(range(len(means)),means,yerr=yerrs, capsize=3, picker=True)
    ax.set_xticklabels([None,'1992','1993','1994','1995'])
    ax.locator_params('x',nbins=8)
    #plt.setp(y, fc='k', fill=False)
    
    plt.draw()
    #plt.setp(y, height=20000)
    #fig.canvas.draw()
    
fig.canvas.mpl_connect('pick_event', onpick)
0 Answers
Related