事件选择以更新条形图属性

Event Pick to update BarChart Attributes

论坛新人!

我正在尝试为家庭作业问题创建一个交互式条形图 – 我想知道如果不使用其他人的解决方案(比如这个很棒的代码 !)我哪里出错了

我单击图表以生成具有新 y 值的参考线并更改条形的颜色。为简单起见,我仅使用两种颜色进行调试并与平均值进行比较(当 y > 平均值时,y < 平均值)。除了下面的两个代码外,我还尝试清除图表并在 onclick 函数中重新绘制它并编写一个单独的函数,尽管不确定如何调用它......任何指导将不胜感激 - 我'我不确定这些部分是如何组合在一起的,因此很难将其分解以进行故障排除。

df=pd.DataFrame({'mean':[40000,50000,20000,60000,3000],'CI':[4000,4000,3000,1000,200]},index=['A','B','C','D','E'])
df=df.T

fig, ax = plt.subplots()
bars = ax.bar([1,2,3,4,5], df.loc['mean'])
    
#Set horizontal line
hline = ax.axhline(y=20000, c='red', linestyle='--')
ax.set_xticks([1,2,3,4,5])
ax.set_xticklabels(df.columns)

def onclick(event):
    hline.set_ydata([event.ydata, event.ydata])
    df2.loc['y']=event.ydata
    for val in df2.loc['y']:
        if df2.loc['y'] < df2.loc['mean']:
            col.append('red')
        else:
            col.append('white')
fig.canvas.mpl_connect('button_press_event', onclick)
    

也试过

def onclick(event):
    #provide y data, based on where clicking.  Note to self:  'xdata' would give slanted line
    hline.set_ydata([event.ydata, event.ydata])
    df2.loc['y']=event.ydata
    for bar in bars:
        if event.ydata < df2.loc['mean']:
            bar.set_color('red')
        else:
            bar.set_color('white')
    return result

主要问题是你从不重绘canvas,所以你向matplotlib传达的每一个变化都不会出现在后端生成的图中。您还必须 update the properties of the rectangles representing the bars - 您在其中一个版本中使用 bar.set_color() 尝试过此操作,该版本同时更改了 facecoloredgecolor,有意或无意。

import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame({'mean':[40000,50000,20000,60000,3000],'CI':[4000,4000,3000,1000,200]},index=['A','B','C','D','E'])
df2=df.T

fig, ax = plt.subplots()
bars = ax.bar(range(df2.loc['mean'].size), df2.loc['mean'])
    
#Set horizontal line
hline = ax.axhline(y=20000, c='red', linestyle='--')
ax.set_xticks(range(df2.columns.size), df2.columns)

def onclick(event):
    #update hline position
    hline.set_ydata([event.ydata])
    #change all rectangles that represent the bars
    for bar in bars:
        #retrieve bar height and compare
        if bar.get_height() > event.ydata:
            #to set the color
            bar.set_color("red")
        else:
            bar.set_color("white")
    #redraw the figure to make changes visible
    fig.canvas.draw_idle()
            
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

输出: