当当网1000本同类别图书价格对比:matplotlib基本使用,plot-线段,bar-条形图,pie-饼图

"""
获取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 )
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值