Reputation: 55
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.
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.
It should be student_id data in the x-axis, and numberpost data in the y-axis.
Anyone can help me how to solve this problem?
Upvotes: 0
Views: 199
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
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