Bokeh是一个专门针对Web浏览器的交互式可视化Python库
1 说明:
=====
1.1 Bokeh是专门针对Web浏览器的交互式、可视化Python绘图库。
1.2 Bokeh,可以做出像D3.js简洁漂亮的交互可视化效果,但是使用难度低于D3.js。
1.3 不需要使用Javascript。
2 官网:
======https://docs.bokeh.org/en/latest/ https://github.com/bokeh/bokeh
3 安装:
=====pip install bokeh #本机安装 sudo pip3.8 install bokeh
4 环境:
=====
华为笔记本电脑、深度deepin-linux操作系统、python3.8和微软vscode编辑器。
5 静态基本作图:
============
5.1 柱状图:
5.1.1 代码:from bokeh.io import output_file, show from bokeh.plotting import figure #数据,支持中文 fruits = ["苹果", "Pears", "Nectarines", "Plums", "Grapes", "Strawberries"] counts = [5, 3, 4, 2, 4, 6] #绘图 p = figure(x_range=fruits, plot_height=350, title="Fruit Counts", toolbar_location=None, tools="") #柱状图,vbar是指垂直柱状图 p.vbar(x=fruits, top=counts, width=0.9) #导出文件:文件名和指定路径, #注意没有这一行,也会自动在代码所在的生成同名的html文件 #output_file("/home/xgj/Desktop/bokeh/bar_basic.html") #展示图 show(p)
5.1.2 图:
5.2 折线图
5.2.1 代码:from bokeh.io import output_file, show from bokeh.plotting import figure #数据,支持中文 fruits = ["苹果", "Pears", "Nectarines", "Plums", "Grapes", "Strawberries"] counts = [5, 3, 4, 2, 4, 6] #绘图 p = figure(x_range=fruits, plot_height=350, title="Fruit Counts", toolbar_location=None, tools="") #柱状图 p.line(x=fruits, y=counts) #展示图 show(p)
5.2.2 图:
5.3 散点图:
5.3.1 代码:#from bokeh.io import output_file, show from bokeh.plotting import figure,output_file, show #同上 #数据,支持中文 fruits = ["苹果", "Pears", "Nectarines", "Plums", "Grapes", "Strawberries"] counts = [5, 3, 4, 2, 4, 6] #绘图 p = figure(x_range=fruits, plot_height=350, title="Fruit Counts", toolbar_location=None, tools="") #柱状图 p.scatter(x=fruits, y=counts,size=20, fill_color="#74add1") #展示图 show(p)
5.3.2 图:
===基本作图方便,优美;比matplotlib简单,暂时介绍到这里===
6 高级作图:
=========
6.1 js_events:调用js事件
6.2 代码:import numpy as np from bokeh import events from bokeh.io import output_file, show from bokeh.layouts import column, row from bokeh.models import Button, CustomJS, Div from bokeh.plotting import figure #定义js和事件 def display_event(p, attributes=[]): style = "float: left; clear: left; font-size: 13px" return CustomJS(args=dict(p=p), code=""" var attrs = %s; var args = []; for (var i = 0; i < attrs.length; i++) { var val = JSON.stringify(cb_obj[attrs[i]], function(key, val) { return val.toFixed ? Number(val.toFixed(2)) : val; }) args.push(attrs[i] + "=" + val) } var line = "" + cb_obj.event_name + "(" + args.join(", ") + ")n"; var text = p.text.concat(line); var lines = text.split("n") if (lines.length > 35) lines.shift(); p.text = lines.join("n"); """ % (attributes, style)) #数据 N = 4000 x = np.random.random(size=N) * 100 y = np.random.random(size=N) * 100 radii = np.random.random(size=N) * 1.5 colors = [ "#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y) ] p = figure(tools="pan,wheel_zoom,zoom_in,zoom_out,reset,tap,lasso_select,box_select") #调用散点图 p.scatter(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None) #容器实例化,宽 p = Div(width=1000) button = Button(label="Button", button_type="success", width=300) layout = column(button, row(p, p)) #注册事件回调 #按钮事件 button.js_on_event(events.ButtonClick, display_event(p)) # LOD事件 p.js_on_event(events.LODStart, display_event(p)) p.js_on_event(events.LODEnd, display_event(p)) # Point events点事件 point_attributes = ["x","y","sx","sy"] p.js_on_event(events.Tap, display_event(p, attributes=point_attributes)) p.js_on_event(events.DoubleTap, display_event(p, attributes=point_attributes)) p.js_on_event(events.Press, display_event(p, attributes=point_attributes)) p.js_on_event(events.PressUp, display_event(p, attributes=point_attributes)) # Mouse wheel event p.js_on_event(events.MouseWheel, display_event(p,attributes=point_attributes+["delta"])) # Mouse move, enter and leave p.js_on_event(events.MouseMove, display_event(p, attributes=point_attributes)) p.js_on_event(events.MouseEnter, display_event(p, attributes=point_attributes)) p.js_on_event(events.MouseLeave, display_event(p, attributes=point_attributes)) # Pan events pan_attributes = point_attributes + ["delta_x", "delta_y"] p.js_on_event(events.Pan, display_event(p, attributes=pan_attributes)) p.js_on_event(events.PanStart, display_event(p, attributes=point_attributes)) p.js_on_event(events.PanEnd, display_event(p, attributes=point_attributes)) # Pinch events pinch_attributes = point_attributes + ["scale"] p.js_on_event(events.Pinch, display_event(p, attributes=pinch_attributes)) p.js_on_event(events.PinchStart, display_event(p, attributes=point_attributes)) p.js_on_event(events.PinchEnd, display_event(p, attributes=point_attributes)) # Selection events p.js_on_event(events.SelectionGeometry, display_event(p, attributes=["geometry", "final"])) show(layout)
6.3 效果图:
6.4 图形总体
6.4.1 代码:from bokeh.core.enums import MarkerType from bokeh.layouts import row from bokeh.models import ColumnDataSource, Panel, Tabs from bokeh.plotting import figure, output_file, show from bokeh.sampledata.iris import flowers source = ColumnDataSource(flowers) def make_plot(title, marker, backend): p = figure(title=title, plot_width=350, plot_height=350, output_backend=backend) p.scatter("petal_length", "petal_width", source=source, color="blue", fill_alpha=0.2, size=12, marker=marker) return p tabs = [] for marker in MarkerType: p1 = make_plot(marker, marker, "canvas") p2 = make_plot(marker + " SVG", marker, "svg") p3 = make_plot(marker + " GL", marker, "webgl") tabs.append(Panel(child=row(p1, p2, p3), title=marker)) #output_file("marker_compare.html", title="Compare regular, SVG, and WebGL markers") show(Tabs(tabs=tabs))
6.4.2 效果图
===一般基本作图是小白和普通人需要的掌握的,下次重点讲===
7 机器学习:scikit-learn project
========================
7.1 代码:import numpy as np from sklearn import cluster, datasets from sklearn.preprocessing import StandardScaler from bokeh.layouts import column, row from bokeh.plotting import figure, output_file, show print(" *** This example may take several seconds to run before displaying. *** ") print(" *** 该示例展示前需要等待几秒. *** ") N = 50000 PLOT_SIZE = 400 # generate datasets. np.random.seed(0) noisy_circles = datasets.make_circles(n_samples=N, factor=.5, noise=.04) noisy_moons = datasets.make_moons(n_samples=N, noise=.05) centers = [(-2, 3), (2, 3), (-2, -3), (2, -3)] blobs1 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.4, random_state=8) blobs2 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.7, random_state=8) colors = np.array([x for x in ("#00f", "#0f0", "#f00", "#0ff", "#f0f", "#ff0")]) colors = np.hstack([colors] * 20) # create clustering algorithms dbscan = cluster.DBSCAN(eps=.2) birch = cluster.Birch(n_clusters=2) means = cluster.MiniBatchKMeans(n_clusters=2) spectral = cluster.SpectralClustering(n_clusters=2, eigen_solver="arpack", affinity="nearest_neighbors") affinity = cluster.AffinityPropagation(damping=.9, preference=-200) # change here, to select clustering algorithm (note: spectral is slow) algorithm = dbscan # <- SELECT ALG plots =[] for dataset in (noisy_circles, noisy_moons, blobs1, blobs2): X, y = dataset X = StandardScaler().fit_transform(X) # predict cluster memberships algorithm.fit(X) if hasattr(algorithm, "labels_"): y_pred = algorithm.labels_.astype(np.int) else: y_pred = algorithm.predict(X) p = figure(output_backend="webgl", title=algorithm.__class__.__name__, plot_width=PLOT_SIZE, plot_height=PLOT_SIZE) p.scatter(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), alpha=0.1,) plots.append(p) # generate layout for the plots layout = column(row(plots[:2]), row(plots[2:])) output_file("clustering.html", title="clustering with sklearn") show(layout)
7.2 效果图:
===自己整理并分享出来===
喜欢的就点赞、转发、评论、关注和收藏。