from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:password@localhost/db_name")
We will use the connection string object my_conn in our query.
query="SELECT class,COUNT( * ) number FROM student GROUP BY class"
df = pd.read_sql(query,my_conn)
lb= [row for row in df['class']] # Labels of graph
plot=df.plot.pie(title="Students",y='number',
labels=lb,autopct='%1.0f%%')
Full code is here.
import pandas as pd # import Pandas library
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://usrid:password@localhost/my_db")
query="SELECT class,COUNT( * ) number FROM student GROUP BY class"
df = pd.read_sql(query,my_conn)
lb= [row for row in df['class']] # Labels of graph
plot=df.plot.pie(title="Students ",y='number',labels=lb,autopct='%1.0f%%')
Pie Chart
import pandas as pd
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
query="SELECT class,COUNT(*) number FROM student GROUP BY class"
df = pd.read_sql(query,my_conn)
plot=df.plot.bar(title="Student Number",x='class');
Bar graph
plot=df.plot.barh(title="Student Number",x='class');
import pandas as pd # import Pandas library
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
query="SELECT class,MAX(mark) max, AVG(mark) avg FROM student GROUP BY class"
df = pd.read_sql(query,my_conn)
plot=df.plot.bar(title="Student Number",x='class');
import pandas as pd # import Pandas library
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
query="SELECT class,\
sum(CASE WHEN gender ='male' THEN 1 ELSE 0 END) as Male,\
sum(CASE WHEN gender ='Female' THEN 1 ELSE 0 END) as Female\
FROM student group by class"
df = pd.read_sql(query,my_conn)
plot=df.plot.bar(title="Student Number",x='class',stacked=True);
plot=df.plot.line(title="Student Number",x='class',y='number')
query="SELECT mark FROM student"
df = pd.read_sql(query,my_conn)
plot=df.plot.density();
query="SELECT COUNT( * ) number,avg(mark) avg FROM student GROUP BY class"
df = pd.read_sql(query,my_conn)
plot=df.plot.scatter(title="Average Vs Number ",x='avg',y='number')
plot=df.plot.pie(title="Students",y='number',
labels=lb,autopct='%1.0f%%')
fig = plot.get_figure()
fig.savefig("D:\\my_data\\output2.png")
Pandas plot plot.barh()
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.