Python + Matplotlib生成图表
前言:原来准备拿excel生成,奈何30w数据一开excel就崩,所以就去简单学习了一下python。感觉还挺好用,就顺手记录一下。
- 起因
-
Python连接数据库查询数据转饼图
import pandas as pd import matplotlib.pyplot as plt import pymysql # 联合国儿童基金会 plt.rcParams['font.sans-serif']=['Simhei'] # 连接数据库 conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='mydb') cur = conn.cursor() # 查询数据 sql = 'SELECT title, count(*) FROM dpo_import GROUP BY title' cur.execute(sql) data = cur.fetchall() # 转换数据 df = pd.DataFrame(data, columns=['title', 'count']) # 饼图的标签 可以自定义,这里没用到直接用数据库查询的标签 labels = ['先生', '女士', '小朋友', '未知'] # 绘制饼图 plt.pie(df['count'], labels=df['title'], autopct='%1.2f%%') plt.title('人群比例') plt.show() # 关闭数据库连接 conn.close()
-
捐款人数TOP10
import pandas as pd import matplotlib.pyplot as plt import pymysql # 联合国儿童基金会 plt.rcParams['font.sans-serif']=['Simhei'] # 连接数据库 conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='mydb') cur = conn.cursor() # 查询数据 sql = 'SELECT city, count(*) as counts FROM dpo_import GROUP BY city ORDER BY counts DESC LIMIT 0, 10' cur.execute(sql) data = cur.fetchall() # 转换数据 df = pd.DataFrame(data, columns=['city', 'count']) # 绘制饼图 plt.bar(df['city'], df['count']) plt.title('捐款地区TOP10') plt.show() # 关闭数据库连接 conn.close()
评论区