updating labels using pylab / matplotlib when refreshing a graph
<p>I have some standard boiler plate code to draw a simple bar graph with a "count" label on top of each bar. I am live updating this bar graph as the data changes. I am able to successfully live update the graph. Here is the code : </p>

<pre><code>fig, ax = plt.subplots()
def my_graph():
    y_pos = np.arange(len(data_list))
    rects1 = ax.bar(y_pos, count_list, 0.28, color='r')
    # plt.bar(y_pos, count_list, 0.28, color='b', align='center', alpha=0.5)
    ax.set_xticks(y_pos, data_list)
    ax.set_xticklabels(data_list, rotation='vertical')
    ax.set_ylabel('Counts')
    ax.set_title('Some stats ')
    plt.plot()
    plt.ylim([0, 50])
    autolabel(rects1)

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height,
            '%d' % int(height), ha='center', va='bottom')
</code></pre>

<p>which as you can see is standard boiler plate code.  In my main I do:</p>

<pre><code>if __name__ == "__main__":
    my_graph()
    plt.ion()
    while True:
        time.sleep(3)
        get_updated_data()
        my_graph()
        plt.pause(0.01)
</code></pre>

<p>get_updated_data will just pull new data and call the code to generate the graph. This is correctly updating the bars. However, the labels added above each bar aren't overwritten. They get "stacked" above each other each time the graph is refreshed. Whats the appropriate way to fix this ? I have tried fig.canvas.draw() but it is not working. Maybe I am adding it in the wrong place. Whats the right approach ?</p>

<p>Thanks</p>

<p>One option is to clear the axes each iteration with <a href="http://matplotlib.org/api/pyplot_api.html?highlight=clf#matplotlib.pyplot.cla" rel="nofollow">cla()</a>. Alternately you could store each text object and remove them when needed. </p>

<pre><code>t = ax.text(0.5,0.5,"label")
plt.pause(3)
t.remove()
fig.canvas.draw()
</code></pre>

python matplotlib