atiqah yusri
atiqah yusri

Reputation: 55

visualize data in bar chart using python

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?

Upvotes: 0

Views: 199

Answers (2)

Energya
Energya

Reputation: 2673

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(), ...

Upvotes: 1

Ray's Web Presence
Ray's Web Presence

Reputation: 474

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.

Upvotes: 0

Related Questions