交互式滑块条形图颜色控制 [英] Interactive Slider Bar Chart Color Control

查看:60
本文介绍了交互式滑块条形图颜色控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四组随机正态分布数.该方法用于绘制条形图,每组的95%置信区间用误差线绘制.

I have four sets of random normal distributed numbers. The means are used to plot bar chart with each set's 95% confidence intervals plotted with errorbar.

给定值y,将为与y的四个范围相对应的条设置四种不同的颜色:1. 平均值的下限;2. 平均到上限;3.低于下;4. 上方.

Given a value y, four different colors will be set to the bars corresponding to the four ranges y is in: 1. lower bound to avg; 2. avg to upper bound; 3. below lower; 4. above upper.

我想使用滑块控制y值并在每次滑动时更新条形颜色,我尝试使用以下代码,但是条形图无法在每次更新时绘制.

I want to use a slider to control the y value and update the bar color each time I slide, I tried to use the following code but the bar charts cannot be plotted every update.

有人可以给我一些想法吗?

Could someone give me some ideas?

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import scipy.stats as st
from matplotlib.widgets import Slider

np.random.seed(12345)

df = pd.DataFrame([np.random.normal(33500,150000,3650), 
                   np.random.normal(41000,90000,3650), 
                   np.random.normal(41000,120000,3650), 
                   np.random.normal(48000,55000,3650)], 
                  index=[1992,1993,1994,1995])

N = len(df.columns)-1  # Degree of Freedom
avg = df.mean(axis=1)  # Mean for each row
std = df.sem(axis=1)  # Unbiased Standard Deviation

year = df.index.map(str)  # Convert to String
conf95 = st.t.ppf(0.95, N)*std  # 95% Confidence Interval

upper = avg + conf95
lower = avg - conf95
colormap = ['blue', 'aqua', 'orange', 'brown']

ini = 39900
chk1 = ini>upper  # Check if y is greater than upper bound: blue
chk2 = ini<lower  # CHeck if y is smaller than lower bound: brown
chk3 = (ini>=lower) & (ini<=avg) # Check if y is in between avg and lower: orange
chk4 = (ini>avg) & (ini<=upper) # Check if y is in between avg and upper: aqua


fig, ax =plt.subplots()   
ax.bar(df.index[chk1.values], avg.iloc[chk1.values], width=1, edgecolor='k', color='blue')
ax.bar(df.index[chk2.values], avg.iloc[chk2.values], width=1, edgecolor='k', color='brown')
ax.bar(df.index[chk3.values], avg.iloc[chk3.values], width=1, edgecolor='k', color='orange')
ax.bar(df.index[chk4.values], avg.iloc[chk4.values], width=1, edgecolor='k', color='aqua')
ax.axhline(y=ini,xmin=0,xmax=10,linewidth=1,color='k')

ax.errorbar(df.index, avg, yerr=conf95, fmt='.',capsize=15, color='k')
plt.subplots_adjust(left=0.1, bottom=0.2)
plt.xticks(df.index, year)  # Map xlabel with String
plt.yticks(np.arange(0,max(avg)+1,max(avg)/5))

axcolor = 'lightgoldenrodyellow'
axy = plt.axes([0.1, 0.1, 0.7, 0.03], axisbg=axcolor)

sy = Slider(axy, 'y', 0.1, int(max(upper)+1), valinit=ini)

直到这一步,颜色才能正常工作.然后更新功能不起作用.

Until this step the color works fine. Then the update func does not work thou.

def update(val):
    ax.cla()
    yy = sy.val    
    chk1 = yy>upper
    chk2 = yy<lower
    chk3 = (yy>=lower) & (yy<=avg)
    chk4 = (yy>avg) & (yy<=upper)
    ax.bar(df.index[chk1.values], avg.iloc[chk1.values], width=1, edgecolor='k', color='blue')
    ax.bar(df.index[chk2.values], avg.iloc[chk2.values], width=1, edgecolor='k', color='brown')
    ax.bar(df.index[chk3.values], avg.iloc[chk3.values], width=1, edgecolor='k', color='orange')
    ax.bar(df.index[chk4.values], avg.iloc[chk4.values], width=1, edgecolor='k', color='aqua')
    ax.bar(df.index, avg, width=1, edgecolor='k', color='silver')
    ax.errorbar(df.index, avg, yerr=conf95, fmt='.',capsize=15, color='k')
    ax.axhline(y=yy,xmin=0,xmax=10,linewidth=1,color='k')
    fig.canvas.draw_idle()

sy.on_changed(update)  

真的很感谢您的见解,非常感谢你们!

Really appreciate any insights and Thank you guys very much!

最好的肖恩

推荐答案

直接删除一行

ax.bar(df.index, avg, width=1, edgecolor='k', color='silver')

我不知道为什么要将它放在这里,但是它将在彩色条的顶部绘制一个完整的单色条形图并将其隐藏.

I don't know why you put it there, but it will plot a complete unicolor barchart on top of the colored bars and hide them.

<小时>为了使某些交互成为可能,需要使用交互式后端.因此,当设置%matplotlib inline 模式时,它将无法在IPython中立即使用.您拥有的选项:


In order to make some interaction possible, an interactive backend needs to be used. So it will not work out of the box in IPython when %matplotlib inline mode is set. Options you have:

  • 在IPython Qt控制台或jupyter笔记本中使用%matplotlib笔记本.
  • 在将代码作为脚本运行时使用 GUI 后端,通过添加 plt.show().在 Spyder 中,可以通过在新的专用窗口中运行脚本来确保这一点,如此处绘制的草图.
  • Using %matplotlib notebook in IPython Qt console or jupyter notebook.
  • Using a GUI backend when running code as a script, by adding plt.show(). In Spyder that can be ensured by running the script in a new dedicated window as sketched here.

这篇关于交互式滑块条形图颜色控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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