更改参数后如何自动更改颜色 [英] How to change colors automatically once a parameter is changed

查看:53
本文介绍了更改参数后如何自动更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,条形的颜色随着阈值的改变而改变.我想使用OnMouseMove函数中的y参数,而不是使用阈值并在代码中绘制水平线,以便用户可以更改阈值"的位置.然后,我希望颜色随着y的变化而更新.

In the following code, the color of bars changes as the threshold is changed. Instead of using the threshold and plotting the horizontal line in the code, I want to use the y parameter in the OnMouseMove function so that the user can change the location of "threshold". Then, I want the colors to be updated as the y is changed.

我认为我需要的是观察者模式",或者也许是使用动画工具的窍门,但不确定如何实现它.感谢您对如何执行此操作有任何见解.谢谢

I think what I need is called "observer pattern" or perhaps a trick using the animation tools but not sure how to implement it. I appreciate any insight on how to do this. Thanks

%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)

推荐答案

首先,您应该使用一个柱状图和一个axhline(使用更多柱状图将使所有事情变得混乱).您可以通过

First you should use exactly one bar plot and exactly one axhline (using more will make everything chaotic). You can set the colors of the bars via

for bar in bars:
    bar.set_color(..)

,您可以通过line.set_ydata(position)更新轴的位置.

and you can update the axhline's position via line.set_ydata(position).

现在,对于每个鼠标移动事件,您都需要更新斧头的位置,计算百分比并将新颜色应用于条形.因此,这些事情应该在函数中完成,每次触发鼠标移动事件时都会调用该函数.应用这些设置后,需要绘制画布以使其可见.

Now, for every mouse move event you need to update the axhline's position, calculate the percentages and apply a new colors to the bars. So those things should be done in a function, which is called every time the mouse move event is triggered. After those settings have been applied the canvas needs to be drawn for them to become visible.

这是完整的代码.

import pandas as pd
import numpy as np
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()

threshold=420.
bars = plt.bar(range(df.shape[0]), df.mean(axis = 1), color = 'lightslategrey')
axline = 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([])
plt.colorbar(cpick, orientation='horizontal')

def percentages(threshold):
    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)
    return percentages

def update(threshold):
    axline.set_ydata(threshold)
    perc = percentages(threshold)
    for bar, p in zip(bars, perc):
        bar.set_color(cpick.to_rgba(p))

# update once before showing
update(threshold)

def onMouseMove(event):
    if event.inaxes == ax:
        update(event.ydata)
        fig.canvas.draw_idle()

fig.canvas.mpl_connect('motion_notify_event', onMouseMove)

plt.xticks(range(df.shape[0]), df.index, alpha = 0.8)

plt.show()

这篇关于更改参数后如何自动更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆