一、安装Matplotlib
pip3.5 install matplotlib
二、保存图片
保存的时候要将plt.savefig('./test2.jpg')放到了plt.show()之后,否则保存的为空白图片。
先保存,后展示
import matplotlib.pyplot as plt
name_list = ['Monday','Tuesday','Friday','Sunday']
num_list = [1.5,0.6,7.8,6]
num_list1 = [1,2,3,1]
num_list1 = [1,2,3,1]
x =list(range(len(num_list)))
total_width, n = 0.8, 2
width = total_width / n
plt.bar(x, num_list, width=width, label='boy',fc = 'y')
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(x, num_list1, width=width, label='girl',tick_label = name_list,fc = 'r')
plt.legend()
plt.savefig('./test.jpg')
plt.show()
三、连接数据库动态展示
代码如下:
# -*- coding: utf-8 -*-
import pymysqlimport matplotlib.pyplot as plt
db=pymysql.connect(host="master",user='root',passwd="123456",port=3306,db="lagou",charset='utf8')
cursor=db.cursor()#获取一个游标
sql="select city,need from citys"
cursor.execute(sql)
result=cursor.fetchall() #result为元组
#将元组数据存进列表中
city=[]
need=[]
for x in result:
city.append(x[0])
need.append(x[1])
#直方图
plt.bar(range(len(need)), need, color='steelblue', tick_label=city)
plt.xlabel("城市名")
plt.ylabel("数量")
plt.title("城市职位需求图")
for x,y in enumerate(need):
plt.text(x-0.4, y+0.4, '%s' % y)
plt.show()
cursor.close()#关闭游标
db.close()#关闭数据库
四、