首页 > 解决方案 > Trying to plot histogram - overwritting values

问题描述

I'm trying to plot the histogram from list in Telegram bot. I use for it 'finallist', after loop I clear my all list, but it seems that histogram takes all values from previous inputs and plot new histogram with all of them, only changing colors:

import matplotlib.pyplot as plt
import sys
import time
import telepot
from telepot.loop import MessageLoop
import numpy as np
import pylab as pl
import logging
import os

x = list()
l = list()

def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)
    print("Hi, start typing!")

    if content_type == 'text':
        if msg['text'] == 'clean':
            x.clear()
            bot.sendMessage(chat_id, 'Your list is empty. ')
        else:
            if msg['text'] == 'histogram':
                finallist = l[0]
                i=1
                while i < len(l):
                    finallist = finallist + l[i]
                    i = i+1
                bot.sendMessage(chat_id, 'Here is the list of occuring numbers:' + str(finallist).strip(' '))
                fig = pl.hist(finallist)
                plt.savefig('finalplot.png')
                bot.sendPhoto(chat_id=chat_id, photo=open('finalplot.png', 'rb'))
                bot.sendMessage(chat_id, 'This is your histogram.')
                x.clear()
                finallist.clear()
                l.clear()
                os.remove("finalplot.png")
            else:
                x.append(msg['text'])
                l.append([int(i) for i in str(msg['text'])])
                bot.sendMessage(chat_id, 'Your list is: ' + str(x).strip(' ') + str(l).strip(' '))


TOKEN = 'mytoken'  # get token from command-line

bot = telepot.Bot(TOKEN)
MessageLoop(bot, handle).run_as_thread()
print('Listening ...')

# Keep the program running.
while 1:
    time.sleep(10)

标签: pythonhistogramtelegramoverwrite

解决方案


推荐阅读