python练习题之jupyter 可视化输出房价数量

题目: 从数据库中取出之前爬取的房租信息,根据数据按照合适的价格区间,用charts生成柱状图在页面上显示每个价格区间的房源数量。

代码如下:

import pymongo
import charts
​
client = pymongo.MongoClient("localhost", 27017)
​
databases = client['duanzu_info']
​
info_table = databases['info_table']
​
# 根据你的数据按照合适的价格区间用charts生成柱状图在页面上显示每个价格区间的房源数量,
# 下载页面保存(方法:File->Download as->HTML),将HTML文件以你的名字拼音命名上传。
# 从数据库中取出
price_lists = []
a = []
b = []
c = []
d = []
e = []
price_interval = ["0~100", "100~500", "500~1000", ">=1000"]
for item in info_table.find():
    price_lists.append(float(item['price'].split("万")[0]))
​
for item in price_lists:
    if item <= 100:
        a.append(item)
    elif item<=500:
        b.append(item)
    elif item<= 1000:
        c.append(item)
    else:
        d.append(item)
​
​
e.append(len(a))
e.append(len(b))
e.append(len(c))
e.append(len(d))
print(e)
​
​//生成器,这里按charts的柱状图格式生成的每个对象
def data_gen(types):
    length = 0
    if length < len(e):
        for interval,time in zip(price_interval,e):
            data = {
                "name":interval,
                "data":[time],
                "type":types
            }
            yield data
            length += 1
​
​
series = [data for data in data_gen("column")]
​
​
charts.plot(series,show="inline",options=dict(title=dict(text ='不同价格区间的房源数量')))
​
# charts.plot(series,show="inline")
​

结果如下: 

python练习题之jupyter 可视化输出房价数量_第1张图片

注意点:

1.python3.7安装charts有坑,直接pip install charts后,使用会报错。 解决方法见另外博客《python3.7安装charts库》https://blog.csdn.net/Aarenliyuan/article/details/84139909:

python练习题之jupyter 可视化输出房价数量_第2张图片

 2.如要生成饼状图等其他类型,需要改写data_gen函数,按照具体的可视化图像的类型,定义字典data,详情可视化类型,可见highcharts:https://www.hcharts.cn/demo/highcharts

你可能感兴趣的:(Python)