【发布时间】:2017-03-31 05:24:48
【问题描述】:
在以下代码中,条形图的颜色会随着阈值的变化而变化。我不想在代码中使用阈值并绘制水平线,而是想在 OnMouseMove 函数中使用 y 参数,以便用户可以更改“阈值”的位置。然后,我希望颜色随着 y 的变化而更新。
我认为我需要的是所谓的“观察者模式”,或者可能是使用动画工具的技巧,但不知道如何实现它。我很感激任何关于如何做到这一点的见解。谢谢
%matplotlib notebook
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.colors as mcol
import matplotlib.cm as cm
import matplotlib.pyplot as plt
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(335,1500,300),
np.random.normal(410,900,300),
np.random.normal(410,1200,300),
np.random.normal(480,550,300)],
index=[1,2,3,4])
fig, ax = plt.subplots()
plt.show()
bars = plt.bar(range(df.shape[0]), df.mean(axis = 1), color = 'lightslategrey')
fig = plt.gcf()
threshold=420
plt.axhline(y = threshold, color = 'grey', alpha = 0.5)
cm1 = mcol.LinearSegmentedColormap.from_list("Test",["b", "white", "purple"])
cpick = cm.ScalarMappable(cmap=cm1)
cpick.set_array([])
percentages = []
for bar in bars:
percentage = (bar.get_height()-threshold)/bar.get_height()
if percentage>1: percentage = 1
if percentage<0: percentage=0
percentages.append(percentage)
cpick.to_rgba(percentages)
bars = plt.bar(range(df.shape[0]), df.mean(axis = 1), color = cpick.to_rgba(percentages))
plt.colorbar(cpick, orientation='horizontal')
def onMouseMove(event):
ax.lines = [ax.lines[0]]
plt.axhline(y=event.ydata, color="k")
fig.canvas.mpl_connect('motion_notify_event', onMouseMove)
plt.xticks(range(df.shape[0]), df.index, alpha = 0.8)
【问题讨论】:
-
year_avg 的值是多少?
-
df.mean(axis = 1)。谢谢。那是一个错误。刚刚更正了。
标签: python matplotlib