用户点击图表,图表根据事件的数据发生变化
The user clicks on the graph and the graph changes based on ydata of te event
下面的代码应该根据 on_click
事件的 ydata 更新图形(更改条形的颜色)。不知怎的,颜色并没有像想象的那样变化。此外,每次单击图形时,我都使用 'ax.clear()'
刷新重绘条形和线条。知道这段代码有什么问题吗?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import cm
import pandas as pd
# Use the following data for this assignment:
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])
fig, ax = plt.subplots()
#Plotting the Bar chart
mean = df.mean(axis = 1)
std = df.std(axis = 1)
n= df.shape[1]
yerr = 1.96*std/np.sqrt(3650)
plt.bar(range(df.shape[0]), mean, yerr = yerr, color = 'grey',capsize=10, alpha = 0.5)
plt.xticks(range(len(df.index)), df.index)
plt.title('Proportion of confidence interval lying below the threshold value')
plt.ylabel('Number of votes')
#Click on the graph to choose a value, the color of the bar change based on the yvalue
colourofbars = []
norm = None
cmap = plt.cm.get_cmap('RdYlBu')
dict = {mean[x]: yerr[x] for x in list(df.index)}
def onclick(event):
val = event.ydata
global colourofbars
global norm
#Defining the condition based on the ydata
for key,value in dict.items():
if val > (key+(value)):
colour = 0
colourofbars.append(colour)
elif val < (key-(value)):
colour = 1
colourofbars.append(colour)
elif ((key+(value))> val > (key-(value))):
colour = ((key+(value))-val)/((key+value)-(key-value))
colourofbars.append(colour)
ax.clear()
norm = matplotlib.colors.Normalize(vmin=min(colourofbars),vmax=max(colourofbars), clip=False)
#Plotting the colored bar chart
plt.bar(range(df.shape[0]), mean, yerr = yerr, capsize=10, alpha = 0.5, color=cmap(norm(colourofbars)))
plt.axhline(y=val,linewidth=1, color='k')
plt.gcf().canvas.draw_idle()
#Adding the colorbar legend
scalarmappaple = cm.ScalarMappable(norm=norm, cmap=cmap)
scalarmappaple.set_array(colourofbars)
plt.colorbar(scalarmappaple)
plt.gcf().canvas.mpl_connect('button_press_event', onclick)
fig.canvas.draw()
在 Jupyter Notebook 中你必须添加
%matplotlib notebook
为了使情节具有交互性(在 import 语句之后添加该行就可以了)。
通过上面的语句我得到了这个情节:
如果我点击绘图中的某处,我会得到:
下面的代码应该根据 on_click
事件的 ydata 更新图形(更改条形的颜色)。不知怎的,颜色并没有像想象的那样变化。此外,每次单击图形时,我都使用 'ax.clear()'
刷新重绘条形和线条。知道这段代码有什么问题吗?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import cm
import pandas as pd
# Use the following data for this assignment:
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])
fig, ax = plt.subplots()
#Plotting the Bar chart
mean = df.mean(axis = 1)
std = df.std(axis = 1)
n= df.shape[1]
yerr = 1.96*std/np.sqrt(3650)
plt.bar(range(df.shape[0]), mean, yerr = yerr, color = 'grey',capsize=10, alpha = 0.5)
plt.xticks(range(len(df.index)), df.index)
plt.title('Proportion of confidence interval lying below the threshold value')
plt.ylabel('Number of votes')
#Click on the graph to choose a value, the color of the bar change based on the yvalue
colourofbars = []
norm = None
cmap = plt.cm.get_cmap('RdYlBu')
dict = {mean[x]: yerr[x] for x in list(df.index)}
def onclick(event):
val = event.ydata
global colourofbars
global norm
#Defining the condition based on the ydata
for key,value in dict.items():
if val > (key+(value)):
colour = 0
colourofbars.append(colour)
elif val < (key-(value)):
colour = 1
colourofbars.append(colour)
elif ((key+(value))> val > (key-(value))):
colour = ((key+(value))-val)/((key+value)-(key-value))
colourofbars.append(colour)
ax.clear()
norm = matplotlib.colors.Normalize(vmin=min(colourofbars),vmax=max(colourofbars), clip=False)
#Plotting the colored bar chart
plt.bar(range(df.shape[0]), mean, yerr = yerr, capsize=10, alpha = 0.5, color=cmap(norm(colourofbars)))
plt.axhline(y=val,linewidth=1, color='k')
plt.gcf().canvas.draw_idle()
#Adding the colorbar legend
scalarmappaple = cm.ScalarMappable(norm=norm, cmap=cmap)
scalarmappaple.set_array(colourofbars)
plt.colorbar(scalarmappaple)
plt.gcf().canvas.mpl_connect('button_press_event', onclick)
fig.canvas.draw()
在 Jupyter Notebook 中你必须添加
%matplotlib notebook
为了使情节具有交互性(在 import 语句之后添加该行就可以了)。
通过上面的语句我得到了这个情节:
如果我点击绘图中的某处,我会得到: