Update (or Redraw?) Matplotlib Bar Chart Using Y Value From Onclick
I have a matplotlib bar chart that uses yerr to simulate a box plot. I would like to click on this bar chart get the y value for this click draw a red horizontal line at this y va
Solution 1:
You want to recalculate the ttests
using the new y value inside onpick
. Then, you can recalculate the colors in the same way as you did before. You can then loop over the bars created with ax.bar
(here I save them as self.bars
for easy access), and use bar.set_facecolor
with the newly calculated color.
I also added a try, except construct to change the yvalue of the line if you click a second time, rather than create a new line.
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from scipy.stats import ttest_1samp
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])
classPointPicker(object):
def__init__(self, df, y=0):
# Store reference to the dataframe for access later
self.df = df
# moments for bar chart "box plot"
mus = df.mean(axis=1)
sigmas = df.std(axis=1)
obs = df.count(axis=1)
ses = sigmas / np.sqrt(obs - 1)
err = 1.96 * ses
Nvars = len(df)
# map t-ststistics to colors
ttests = ttest_1samp(df.transpose(), y)
RdBus = plt.get_cmap('RdBu')
colors = RdBus(1 / (1 + np.exp(ttests.statistic)))
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
# bar chart "box plot". Store reference to the bars here for access later
self.bars = self.ax.bar(
list(range(Nvars)), mus, yerr=ses, capsize=20, picker=5, color=colors)
plt.xticks(list(range(Nvars)), df.index)
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='on', labelbottom='on')
plt.gca().get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
plt.title('Random Data for 1992 to 1995')
self.fig.canvas.mpl_connect('pick_event', self.onpick)
self.fig.canvas.mpl_connect('key_press_event', self.onpress)
defonpress(self, event):
"""define some key press events"""if event.key.lower() == 'q':
sys.exit()
defonpick(self,event):
x = event.mouseevent.xdata
y = event.mouseevent.ydata
# If a line already exists, just update its y value, else create a horizontal linetry:
self.line.set_ydata(y)
except:
self.line = self.ax.axhline(y=y, color='red')
# Recalculate the ttest
newttests = ttest_1samp(df.transpose(), y)
RdBus = plt.get_cmap('RdBu')
# Recalculate the colors
newcolors = RdBus(1 / (1 + np.exp(newttests.statistic)))
# Loop over bars and update their colorsfor bar, col inzip(self.bars, newcolors):
bar.set_facecolor(col)
self.fig.canvas.draw()
if __name__ == '__main__':
#plt.ion()
p = PointPicker(df, y=32000)
plt.show()
Here's some example output:
Post a Comment for "Update (or Redraw?) Matplotlib Bar Chart Using Y Value From Onclick"