0

This is my data inside my PostgreSQL. I need to create a bar chart (y-axis: number of post, x-axis: student_id). so I run SQL Script in Python and visualise using python.

enter image description here

here is my code:

import psycopg2
import pandas as pd
import matplotlib.pyplot as plt

con = psycopg2.connect(
            host = "",
            database="",
            port="",
            user = "",
            password = "")

cur = con.cursor()

query= 'select student_id, count(student_id) as numberpost from forum group by student_id'

df=pd.read_sql(query,con)

plt.bar(x=df['student_id'],
        height=df['numberpost'])
plt.xticks(rotation = 45)
plt.show()

However, I didn't get the output as I want. This is the output that I get.

enter image description here

It should be student_id data in the x-axis, and numberpost data in the y-axis.

enter image description here

Anyone can help me how to solve this problem?

5
  • The problem seems to be the large range of student_id values, as it's read as integers. Maybe try passing them as strings instead? So plt.bar(x=df['student_id'].to_string(), ... Commented Oct 15, 2020 at 22:58
  • @Energya, I did that, but the output I got as below: <img src="drive.google.com/file/d/1yYFqoUUehj2aqTJZKvEt-g2qmQ6-heTG/…"> Commented Oct 17, 2020 at 18:13
  • Then you need to adjust your xticks accordingly, try searching for that Commented Oct 17, 2020 at 18:23
  • alright, thank you :-) Commented Oct 17, 2020 at 18:26
  • I've added my comment as an answer so you can accept it Commented Oct 17, 2020 at 18:30

2 Answers 2

1

The problem seems to be the large range of student_id values, as it's read as integers.

Maybe try passing them as strings instead? So try

plt.bar(x=df['student_id'].to_string(), ...
Sign up to request clarification or add additional context in comments.

Comments

0

I tested this with the code below and it worked fine.

df = pd.DataFrame()
df['student_id'] = [1,2,3,4,5,6,7]
df['numberpost'] = [12,3,4,3,4,5,334]

plt.bar(x=df['student_id'],
        height=df['numberpost'])
plt.xticks(rotation = 45)
plt.show()

My guess is your dataframe does not contain data.

Have you checked to see if the df contains data?

I assume your con variable actually defines parameters (or you left them out for anonymity) as well?

Simply testing with df.head() will tell you if you have results.

1 Comment

I tested using df.head(), I have data in my dataframe. about the con, yes I left them out for anonymity, This is the output when I tested using df.head() drive.google.com/file/d/1Ifg2R7-pmU_TVO6s6y4gebAYK9gcnisT/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.