python爬虫爬取数据进行图形化显示数据(以条形图为例!)

    技术2022-07-11  92

    1.安装新的工具

    pip install matplotlib

    2.编码实现

    import matplotlib.pyplot as plt import math import pymysql import random # 用来正常显示中文标签 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示负号 plt.rcParams['axes.unicode_minus'] = False # 统计不同类别职位数量的对比 connection = pymysql.connect(host='localhost', user='root', password="123456", database='db_2020_jobinfo', port=3306, charset='utf8') # 2.获得游标 cursor = connection.cursor() # 3.执行SQL语句 result = cursor.execute("select avg(meanSalary), jobType from t_job_data group by jobType;") # 4.如果是查询操作,fetchone fetchall() resultSet = cursor.fetchall() connection.close() # 柱状图 xLabel = [] y = [] for row in resultSet: y.append(row[0]) xLabel.append(row[1]) pass x = [i+1 for i in range(len(xLabel))] bars = plt.bar(x, y, width=0.3) for bar in bars: bar.set_color("#" + str(random.randint(100000, 999999))) pass plt.xticks(x, xLabel) for x,y in zip(x, y): plt.text(x, y+0.05, '%.0f(元/月)' % y, ha='center', va= 'bottom') pass plt.xlabel('职位类别') plt.ylabel("元/月") plt.title('不同职位薪资对比图') plt.plot(x, y) plt.grid(linestyle='--') plt.show() # 统计不同类别职位数量的对比 connection = pymysql.connect(host='localhost', user='root', password="root", database='db_2020_jobinfo', port=3306, charset='utf8') # 2.获得游标 cursor = connection.cursor() # 3.执行SQL语句 result = cursor.execute("select count(*), jobType from t_job_data group by jobType") # 4.如果是查询操作,fetchone fetchall() resultSet = cursor.fetchall() connection.close() c = [] x = [] for row in resultSet: x.append(row[0]) c.append(row[1]) pass plt.pie(x, labels=['%s,%.2f%%,总数:%s'% (n, p/sum(x)*100.0, p) for n, p in zip(c, x)]) plt.title('不同的职位类别占比') plt.show() # 点线图,x轴,y轴 # y = x x = [t/10 for t in range(0, 100)] y = [math.sin(t) for t in x] plt.xticks(x, x) plt.yticks(y, y) plt.title('sin') plt.plot(x, y) plt.show()

    3.实现成功

    Processed: 0.019, SQL: 9