一个类包裹几个图的写法,备查
python -m pip install matplotlib
import matplotlib.pylab as plt
import matplotlib
import random
class pllt():
def __init__(self):
matplotlib.rcParams['font.size'] = 10 #字号
matplotlib.rcParams['font.family']='SimHei' #中文显示
def plot_histogram(self): #柱状
x=list(range(7)) #X的数据
y=random.sample(range(1,10),7) #在列表中随机选取7个数作为Y的数据
plt.bar(x,y) #绘制
plt.xlabel('我是X轴')
plt.ylabel('我是Y轴')
plt.title('我是标题')
plt.show()
def plot_line(self): #折线
x = list(range(7))
y = random.sample(range(1, 10), 7)
y2 = random.sample(range(1, 10), 7)
plt.plot(x, y, label='y', marker='.', color='blue')
plt.plot(x, y2, label='y2', marker='*', color='green')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('折线图')
plt.legend() # 图例,用来表示图中线的信息
plt.show()
def plot_pie(self): #饼图
# 这是每个部分的名称
name_list = ['part1', 'part2', 'part3', 'part4']
# 这是每个部分对应的数据,与上述名称列表对应
num_list = [56, 33, 78, 95]
# explode 是用于着重的表示,某个值不为0表示对应某个部分离开圆心的距离
explode = (0, 0, 0.1, 0)
# 每个部分所用的颜色
colors = ['orange', 'yellow', 'lime', 'red']
# 如果画出来的圆是扁的,可以用以下三行代码把圆变成一个正圆
plt.xlim(0.8)
plt.ylim(0.8)
plt.axes(aspect='equal')
plt.pie(num_list, labels=name_list, explode=explode, colors=colors)
plt.title('饼图', fontsize=18)
plt.legend()
plt.show()
def plot_scatter(self): #散点图
x = list(range(7))
y = random.sample(range(1,10), 7)
plt.scatter(x, y)
plt.title('散点图', fontsize=18)
plt.show()
if __name__=='__main__':
a=pllt() #实例化
a.plot_histogram() #柱子
a.plot_line()#折线
a.plot_pie()#饼
a.plot_scatter()#点
如果需要将图片用网页显示,相对简单的办法是把上面的plt.show()
更换成plt.savefig('path路径')这样把图片保存下来,然后直接用网页显示该图片。
补充:上面方案保存下来的图片可以通过PIL打开再进行响应式视图导入例子如下:
下面这个函数可以生成一个饼子图保存在d:/nini2/static/3.jpg中
def plot_pie(self): #饼图
# 这是每个部分的名称
name_list = ['张松林', '窦军', '任海涛', '赵明轩',5,6,7,8,9,10]
# 这是每个部分对应的数据,与上述名称列表对应
num_list = [1,2,3,4,5,6,7,8,9,10]
# explode 是用于着重的表示,某个值不为0表示对应某个部分离开圆心的距离
explode = (0.1, 0.1, 0.1, 0.05,0,0,0,0,0,0)
# 每个部分所用的颜色
colors = ['orange', 'yellow', 'lime', 'red','green','black', 'yellow', 'lime', 'red','yellow']
# 如果画出来的圆是扁的,可以用以下三行代码把圆变成一个正圆
plt.xlim(0.8)
plt.ylim(0.8)
plt.axes(aspect='equal')
plt.pie(num_list, labels=name_list, explode=explode, colors=colors)
plt.title('饼图', fontsize=18)
plt.legend()
plt.savefig('d:/nini2/static/3.jpg')
主显示页面如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>本月奖金分配饼图</h1>
<img src=" {{ url_for('get_image') }}" alt="">
</body>
</html>
通过index()路由调用主显示页面然后在HTML中url_for()函数
就可以触发get_image()路由动作
@app.route('/')
def index():
return render_template('index.html')
@app.route('/image')
def get_image():
a=pllt()#实例化饼图
a.plot_pie()#画个饼图,并在内部执行了保存
im = Image.open(r"d:/nini2/static/3.jpg") #把保存的这个饼图再通过IM读出来,这样就可以变通一下写入页面了
#将image对象转二进制
## 先弄个buffer容器
buffer = BytesIO()
## 把im存入buffer 容器中, 后面指定好图片类型
im.save(buffer,'JPEG')
## 从容器中读出图片
buf_bytes = buffer.getvalue()
## 将读出内容装入自制响应体
response = make_response(buf_bytes)
## 在响应体前添加响应头并指明类型
response.headers['Content-Type']= 'image/jpg'
## okok了
return response
这样可以提高灵活性,应该还有更好的方案,等探索到了再记录