Table of contents
Initialize the Flask framework and set up routing
Histogram analysis of housing average price in each administrative area
Pie chart of the proportion of houses in each area range
1. Actual combat scenarios
Flask and echarts use visual charts such as histograms and line charts to display second-hand housing statistics
2. Knowledge points
python basic syntax
Python file read and write
pandas data processing
flask web framework
echarts chart
jinja template
3. Rookie actual combat
Initialize the Flask framework and set up routing
'''
Description: 分页读取并显示 csv 文件数据
'''
from math import ceil
import csv
import json
from flask import Flask, render_template, request, redirect, jsonify
from spiders.file_manager import FileManager
# 初始化框架
web = Flask(__name__)
@web.route('/')
def index():
# 首页
return redirect('/list')
@web.route('/table/<int:page_num>')
def table(page_num):
# 分页读取并显示 csv 文件数据
file_manager = FileManager()
file = file_manager.get_data_file_path("tao365_detail.csv")
# 若不指定limits默认为 5
limits = request.args.get('limits', 5, type=int)
def show_csv(reader, page=page_num, limits=limits):
# 内部函数,根据limits和所在页数生成数据
df = []
for row in reader:
if page_num * limits >= (reader.line_num - 1) > (page_num - 1) * limits:
df.append(row)
return df
with open(file, 'r+', encoding='utf-8') as f:
# 计算页面数
row_length = len(f.readlines()) - 1
pages = int(ceil(row_length / limits))
with open(file, 'r+', encoding='utf-8') as f:
# 计算数据
reader = csv.reader(f)
next(reader)
df = show_csv(reader, page_num, limits)
# 加载模版和模版数据
return render_template('table.html', df=df, pages=pages, page_num=page_num, limits=limits)
@web.route('/table_detail')
def table_detail():
# 二手房详情
row = request.args.get('row').split(',')
return render_template('table_detail.html', row=row)
@web.route('/list')
def list_house():
# 二手房列表
return render_template('list.html')
@web.route('/chart1')
def chart1():
# 柱状图
return render_template('chart1.html')
@web.route('/chartBie')
def chartBie():
# 饼图
return render_template('chartBie.html')
@web.route('/chart_data')
def chart_data():
# 获取图标数据
# 图标类型
type = request.args.get("type")
# 二手房数据
file_name = 'chart00' + type+'.json'
file_manager = FileManager()
file = file_manager.get_data_file_path(file_name)
# file = os.path.join(config.DATA_DIR,'chart00'+ type+'.json' )
with open(file, encoding='utf8') as fp:
data_list = json.load(fp)
return jsonify(data_list)
# 启动 flask web 框架
web.run(debug=True)
Histogram analysis of housing average price in each administrative area
def chart001(self):
# 柱状图 - 展示各行政区房屋均价
# 读取清洗后的数据文件
result_df = self.read_clean_result_file()
# 从字典对象导入数据
df = pd.DataFrame(result_df)
# 根据地址分组并计算每平米的平均价
mean_data = df.groupby(['地址'], as_index=False)['每平方价格'].agg({'每平方价格': 'mean'}).round()
# 取出地址列数据
address = mean_data['地址'].unique()
# 取出每平方价格列数据
price = mean_data['每平方价格'].unique()
# 定义表格顶部title
title = "各行政区房屋均价展示"
# 定义表格顶部说明
text = self.top_text
# 定义图表title
chart_title = '各行政区房屋均价展示'
# 定义图表横坐标
chart_x = '所在地区'
# 定义图表纵坐标
chart_y = '房屋均价'
# 定义图表单位
unit = '元'
# 定义图表类型
types = 'bar'
# 组装图表json数据
data_json = {
'data1': address.tolist(),
'data2': price.tolist(),
'title': title,
'text': text,
'chartTitle': chart_title,
'chartX': chart_x,
'chartY': chart_y,
'unit': unit,
'type': types
}
# 将json数据写入文件
with open('../data/chart001.json', 'w', encoding='utf-8') as write_f: # 打开本地文件
json.dump(data_json, write_f, indent=4, ensure_ascii=False) # python对象转换成json对象
echarts rendering histogram
function drawCharts(data) {
var optionMap = {
title: {
text: data.chartTitle,
left: 'center',
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
},
toolbox: {
feature: {
saveAsImage: {
title: ''
}
}
},
xAxis: {
type: 'category',
name: data.chartX,
data: data.data1
},
yAxis: {
type: 'value',
name: data.chartY,
axisLabel: {
formatter: '{value} ' + data.unit
}
},
series: [{
data: data.data2,
type: data.type
}]
};
//初始化echarts实例
var myChart = echarts.init(document.getElementById('dom1'));
//使用制定的配置项和数据显示图表
myChart.setOption(optionMap);
}
Pie chart of the proportion of houses in each area range
def chart006(self):
# 饼状图 - 南京各面积区间房屋数量占比图函数
# 读取清洗后的数据文件
result_df = self.read_clean_result_file()
# 从字典对象导入数据
df = pd.DataFrame(result_df)
# 定义各面积区间
area_level = [0, 50, 100, 150, 200, 250, 300, 350, 400, 1500]
# 标识分后bins
label_level = ['小于50', '50-100', '100-150', '150-200', '200-250', '250-300', '300-350', '350-400', '大于400']
# 数据从最大值到最小值进行等距划分
area_cut = pd.cut(df['建筑面积'], area_level, labels=label_level)
# 获取等距划分后的数据
df_area = area_cut.value_counts()
# 获取各区间数据
area = df_area.index.tolist()
# 获取各区间房屋数量
count = df_area.values.tolist()
# 拼接图表所需数据
arr = []
for k, i in enumerate(area):
arr.append({'name': i, 'value': count[k]})
# 定义表格顶部title
title = "面积区间房屋数量占比图"
# 定义表格顶部说明
text = self.top_text
# 定义图表标题
chart_title = '各面积区间房屋数量占比图'
# 定义图表名称
chart_name = '各面积区间房屋数量占比图'
# 组装图表json数据
data_json = {
'data1': arr,
'title': title,
'text': text,
'chartTitle': chart_title,
'chartName': chart_name,
}
# 将json数据写入文件
with open('../data/chart006.json', 'w', encoding='utf-8') as write_f: # 打开本地文件
json.dump(data_json, write_f, indent=4, ensure_ascii=False) # python对象转换成json对象
echarts rendering pie chart
function drawCharts(data) {
var optionMap = {
title: {
text: data.chartTitle,
left: 'center',
},
tooltip: {
trigger: 'item'
},
toolbox: {
feature: {
saveAsImage: {
title: ''
}
}
},
legend: {
orient: 'vertical',
left: 'left'
},
series: [{
name: data.chartName,
type: 'pie',
radius: '50%',
data: data.data1,
itemStyle: {
normal: {
label: {
show: true,
formatter: '{b} : {d}%'
},
labelLine: {
show: true
}
}
},
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
};
//初始化echarts实例
var myChart = echarts.init(document.getElementById('dom1'));
//使用制定的配置项和数据显示图表
myChart.setOption(optionMap);
}
operation result
run screenshot
* Serving Flask app 'app_tao05'
* Debug mode: on
* Running on http://127.0.0.1:5000
Open http://127.0.0.1:5000 in the browser
data example
Analysis of the average price of housing in each region
The proportion of the number of houses in each area range
Average house price statistics by region
Average construction area of second-hand houses in each region
Source link
https://download.csdn.net/download/qq_39816613/87374676
Rookie actual combat, keep learning!