2017-04-11 70 views
0

我有一個條形圖。我想讓它在上下移動光標時改變顏色(所以基於y值)。我處於可以製作顏色值的離散列表並在每次點擊時更新圖形的點。但我仍然不知道如何讓它連續運動。如何在鼠標移動時動態改變圖形的顏色?

import matplotlib.pyplot as plt 
from math import floor 

def hex_to_RGB(hex): 


# Pass 16 to the integer function for change of base 
    return [int(hex[i:i + 2], 16) for i in range(1, 6, 2)] 


def RGB_to_hex(RGB): 
    # Components need to be integers for hex to make sense 
    RGB = [int(x) for x in RGB] 
    return "#" + "".join(["0{0:x}".format(v) if v < 16 else 
          "{0:x}".format(v) for v in RGB]) 


def color_dict(gradient): 
    return {"hex": [RGB_to_hex(RGB) for RGB in gradient], 
      "r": [RGB[0] for RGB in gradient], 
      "g": [RGB[1] for RGB in gradient], 
      "b": [RGB[2] for RGB in gradient]} 


def linear_gradient(start_hex, finish_hex="#FFFFFF", n = 100): 
    # Starting and ending colors in RGB form 
    s = hex_to_RGB(start_hex) 
    f = hex_to_RGB(finish_hex) 
    # Initilize a list of the output colors with the starting color 
    RGB_list = [s] 
    # Calcuate a color at each evenly spaced value of t from 1 to n 
    for t in range(1, n): 
     # Interpolate RGB vector for color at the current value of t 
     curr_vector = [ 
      int(s[j] + (float(t)/(n - 1)) * (f[j] - s[j])) 
      for j in range(3)] 
     # Add it to our list of output colors 
     RGB_list.append(curr_vector) 

    return color_dict(RGB_list) 

WtoR = linear_gradient('#FFFFFF', '#FF0000')['hex'] 
# -------------------------------- PLOTTING ----------------------------------------- 

width = 1 

plt.figure() 

plt.bar(1, 100, width, color = 'white', align = 'center') 

def onclick(event): 
    plt.cla() 
    plt.clf() 
    y = event.ydata 
    plt.bar(1, 100, width, color = str(WtoR[floor(y)]), align = 'center') 
    plt.draw() 
plt.gcf().canvas.mpl_connect('button_press_event', onclick) 

plt.show() 

回答

1

TL/DR;改變你的onclick代碼:

def onmotion(event): 
    plt.cla() 
    plt.clf() 
    plt.gca() 
    y = event.ydata 
    if y: 
     plt.bar(1, 100, width, color = str(WtoR[int(y)]), align = 'center') 
     plt.draw() 
plt.gcf().canvas.mpl_connect('motion_notify_event', onmotion) 

您已經註冊,只要你收到一個按鈕按下事件稱爲你的onclick功能。一旦鼠標移動就立即更新,您應該聽運動通知事件。

但是,對於這個事件,您不一定會得到y值(如果您不在圖的座標軸內),因此只有在有y值的情況下才有條件地更新。

此外,離開窗口時,看起來軸被禁用爲matplotlib。這意味着它們必須通過plt.gca()調用重新激活。

作爲一個說明,對於我在python 2.7中沒有工作來索引與floor()函數的值的數組。我必須使用int()來代替,但這可能在python 3中有所不同。

此外,每次調用回調時都會重繪條形圖。尋找可能性來獲得第一個條形碼的id並且僅更新顏色可能是值得的。這可能會更快,因爲它可能需要更少的計算機。