使用python bokeh 进行作图,可交互(可以实时查看点对于的数据)

数据整理步骤:
1.从数据度读取联通数据
2.整理数据,格式、类型等
3.按照折线图可视化

模拟数据点,最终形式:可实时查看对应的点的数据

模拟数据图表

from bokeh.plotting import figure, show,output_notebook
from bokeh.models import HoverTool
from bokeh.models import BasicTickFormatter
import datetime

datetime_list = list(datetime.datetime.now() + datetime.timedelta(days=-(i+1)) for i in range(10))
date_list = list(dt.strftime('%Y-%m-%d') for dt in   datetime_list)
value_list = list(np.random.randint(100,size =10))
data_dic = {'date_id':date_list,"value":value_list}

data = pd.DataFrame(data_dic)
data = data.sort_values('date_id')
data['date_id'] = pd.to_datetime(data.date_id,format="%Y-%m-%d") 


hover = HoverTool(tooltips=[
    ("index", "$index"),
    ("date_id", "@x{%F}"),  # must specify desired format here
    ("value", "$y{F}")]
    ,formatters=dict(x='datetime'),
    # display a tooltip whenever the cursor is vertically in line with a glyph
    mode='vline')


output_notebook()  
p = figure(plot_width=400, plot_height=250, x_axis_type="datetime",tools=[hover],y_range = (0,max(data.value)),title='我是标题')
p.line(data.date_id,data.value,color='navy')
show(p)





以下部分,为真实数据的处理过程,可忽略,本文的功能基本实现方式上面的代码都有。

最终输出结果:可交互图表,可实时查看对应的点的数据

在这里插入图片描述

# coding: utf-8
import psycopg2
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

from bokeh.plotting import figure, show,output_notebook
from bokeh.models import HoverTool
from bokeh.models import BasicTickFormatter


matplotlib.rcParams['font.family']='SimHei'

np.set_printoptions(suppress=True, threshold=np.nan)
pd.set_option('display.max_columns', None)

import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None

# 定义sql
haha_day_sql = """ sql"""
# 取数
conn = psycopg2.connect(database="ircloud_inapp", user="ir_user", password="N9QjpvxxoD^fqgM3", host="113.200.91.99", port="49693")
# online_day_tmp =   pd.read_sql_query(online_day_tmp_sql,con = conn)
# repaired_by_avg_uv =   pd.read_sql_query(sql,con = conn)
liantong_day =  pd.read_sql_query(haha_day_sql,con = conn)
conn.close()
# 数据整理、过滤 top500
# 转换日期格式
haha_day['date_id'] = pd.to_datetime(haha_day.date_id,format="%Y%m%d") 
# 筛出前500的小程序
haha_days_top500 = haha_day.query('rank<=500')
# 按照排名和日期排序
haha_days_top500_sorted = haha_days_top500.sort_values(['rank','date_id'])

# query_by_name = liantong_day.query("wx_name in ('每日优鲜','德邦','苏宁易购','微信支付商户助手','唯品会')")
# 分组,并放入字典中
group_top_lt = haha_days_top500_sorted.groupby('wx_name')
group_dict_top_lt = {}
for x in group_top_lt:
#     print(x[1])
    k = x[1]['rank'].iloc[0]
    v = x[1]
    group_dict_top_lt[k] = v
#     print(x[1].plot(x='date_id',y='uv',title=x[0]+':rank '+ str(k)))
# 定义悬浮组件和对应的字段格式
hover = HoverTool(tooltips=[
    ("index", "$index"),
    ("date_id", "@x{%F}"),  # must specify desired format here
    ("lv", "$y{F}")]
    ,formatters=dict(x='datetime'),
    # display a tooltip whenever the cursor is vertically in line with a glyph
    mode='vline')
# 将字典按照rank排序
sorted_group_dict_lt_top = sorted(group_dict_top_lt.items(),reverse =False )[0:3]
output_notebook()   
for x in sorted_group_dict_lt_top:
#     data = x[1].sort_values('date_id')
#     print(data.wx_name.iloc[0])
    # 拿到对应的 dataframe 数据
    
#     print(data)

    data = x[1]
    # 定义 长宽、X轴数据类型、悬浮工具、y轴范围、标题
    p = figure(plot_width=400, plot_height=250, x_axis_type="datetime",tools=[hover],y_range= (0,max(data.uv)),title='我是标题')
    p.yaxis.formatter = BasicTickFormatter(use_scientific=False)
    p.line(data.date_id,data.uv, color='navy')
    show(p)
    
    # 这是旧方法取展示数据,可视化,速度快,但是没有悬浮窗,查看对应数据的日期
#     print(data.plot(x='date_id',y='uv',title=data['wx_name'].iloc[0]+str(x[0]),ylim=(0,max(data['uv']))))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章