简体   繁体   中英

How to plot top n highest values in a bar graph using matplotlib?

I have realtime data with three values : id, name, salary. I'm plotting a graph for it using name and salary.

def graph():
    con = None
    try:
        con = connect("project.db")
        cursor = con.cursor()
        sql = "select name, salary from employee"
        cursor.execute(sql)
        data = cursor.fetchall()
        name = []
        salary = []
        for i in data:
            name.append(i[0])
            salary.append(i[1])
        plt.bar(name, salary)
        plt.xlabel("Names of Employee")
        plt.ylabel("Salary of Employee")
        plt.title("Top 5 Highest Salaried Employee")
        plt.show()
    except Exception as e:
        showerror("issue ", e)
        con.rollback()
    finally:
        if con is not None:
            con.close()

But my issue is : i get the bar graph for all employees. I only want to plot for the 5 highest paid employees. Is there a way to do this?

You can sort your results from the SQL query by ascending on salary, and then only take the top five results.

Try '''SELECT name, salary FROM employee ORDER BY salary DESC LIMIT 5'''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM