更改参数后如何自动更改颜色

更改参数后如何自动更改颜色,第1张

更改参数后如何自动更改颜色

首先,您应该使用一个柱状图和一个斧头形(使用更多的柱形图会使一切变得混乱)。您可以通过设置条的颜色

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

然后您可以通过更新轴的位置

line.set_ydata(position)

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

这是完整的代码。

import pandas as pdimport numpy as npimport matplotlib.colors as mcolimport matplotlib.cm as cmimport matplotlib.pyplot as pltnp.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 percentagesdef 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 showingupdate(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()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5674460.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存