""" 获取1000本书中不同的价格区间,书籍所占数量 """ import pymysql # 书籍信息来源:https://mp.csdn.net/postedit/90760180
def get_price_count(): # 1-连接 connect = pymysql.Connection(host="localhost", user="root", password="mysql", database="dangdang_book", port=3306, charset='utf8') # 2-找数据 cursor = connect.cursor() select = """ select 价格区间, count(价格) 数量 from (select 价格, case when 价格<20 then "20元以下" when 价格>=20 and 价格<40 then "20元-40元" when 价格>=40 and 价格<60 then "40元-60元" when 价格>=60 and 价格<80 then "60元-80元" when 价格>=80 and 价格<100 then "80元-100元" when 价格>=100 and 价格<150 then "100元-150元" when 价格>=150 and 价格<200 then "150元-200元" when 价格>200 then "200元以上" end "价格区间" from tbl_books) as test group by 价格区间 """ cursor.execute(select) # 3-处理数据 results = cursor.fetchall() # 8行2列 x, y =[] ,[] for result in results: x.append(result[0]) # 存储所有的价格区间 y.append(result[1]) # 存储价格区间的图书数量 # 4-数据库资源关闭 cursor.close() connect.close() return x,y if __name__ == "__main__": x,y = get_price_count() print(x) print(y)
"""
1000本python类别图书价格区间-数量进行对比
1- 折线图
2- 条形图
3- 饼图
"""
from matplotlib import pyplot as plt
from test_books_price import get_price_count
from matplotlib.font_manager import FontProperties
def get_plot(x, y):
fig = plt.figure()
plt.plot(range(len(x)), y, marker="o",
markerfacecolor="r", linestyle=":")
# x轴的刻度
myfont = FontProperties(fname = "source\\lianwen.ttf")
plt.xticks(range(len(x)),x, fontproperties=myfont)
fig.autofmt_xdate(rotation=45)
for index,y_num in enumerate(y):
plt.text(index+0.2, y_num+4,"(%d,%d)"%(index,y_num))
# title xlabel ylabel
plt.show()
def get_bar(x, y):
myfont = FontProperties(fname = "source\\lianwen.ttf") #引入下载字体 -- c:\windows\fonts 或 站长素材网站下载
plt.bar(range(len(x)), y, 0.5, label="价格区间的数量")
# 价格区间的数值
for index , y_num in enumerate(y):
plt.text(index-0.2, y_num+2 ,str(y_num))
plt.legend(prop=myfont)
plt.show()
def get_pie(x, y):
plt.rcParams['font.sans-serif']=['FangSong']
plt.pie(y, autopct="%.2f%%",
labels=x,
shadow=True)
plt.show()
if __name__ == "__main__":
x,y = get_price_count()
get_plot(x,y)
get_bar(x,y)
get_pie(x,y )