今天这篇推文,给大家介绍一下Python中常用且可灵活交互使用的的可视化绘制包- Bokeh,由于网上关于该包较多及官方介绍也较为详细,这里就在不再过多介绍,我们直接放出几副精美的可视化作品供大家欣赏:

在jupyter notebook 中显示

在绘制可视化作品之前需输入:

output_notebook()

即可在jupyter notebook 中交互显示可视化结果。

Bokeh 可视化作品欣赏

  • bar_colormapped

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import Spectral6
from bokeh.plotting import figure
from bokeh.transform import factor_cmapoutput_file("bar_colormapped.html")fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]source = ColumnDataSource(data=dict(fruits=fruits, counts=counts))p = figure(x_range=fruits, plot_height=350, toolbar_location=None, title="Fruit Counts")
p.vbar(x='fruits', top='counts', width=0.9, source=source, legend_field="fruits",line_color='white', fill_color=factor_cmap('fruits', palette=Spectral6, factors=fruits))p.xgrid.grid_line_color = None
p.y_range.start = 0
p.y_range.end = 9
p.legend.orientation = "horizontal"
p.legend.location = "top_center"show(p)

bar_colormapped
  • hexbin

import numpy as npfrom bokeh.io import output_file, show
from bokeh.models import HoverTool
from bokeh.plotting import figuren = 500
x = 2 + 2*np.random.standard_normal(n)
y = 2 + 2*np.random.standard_normal(n)p = figure(title="Hexbin for 500 points", match_aspect=True,tools="wheel_zoom,reset", background_fill_color='#440154')
p.grid.visible = Falser, bins = p.hexbin(x, y, size=0.5, hover_color="pink", hover_alpha=0.8)p.circle(x, y, color="white", size=1)p.add_tools(HoverTool(tooltips=[("count", "@c"), ("(q,r)", "(@q, @r)")],mode="mouse", point_policy="follow_mouse", renderers=[r]
))output_file("hexbin.html")show(p)

hexbin
  • boxplot

import numpy as np
import pandas as pdfrom bokeh.plotting import figure, output_file, show# generate some synthetic time series for six different categories
cats = list("abcdef")
yy = np.random.randn(2000)
g = np.random.choice(cats, 2000)
for i, l in enumerate(cats):yy[g == l] += i // 2
df = pd.DataFrame(dict(score=yy, group=g))# find the quartiles and IQR for each category
groups = df.groupby('group')
q1 = groups.quantile(q=0.25)
q2 = groups.quantile(q=0.5)
q3 = groups.quantile(q=0.75)
iqr = q3 - q1
upper = q3 + 1.5*iqr
lower = q1 - 1.5*iqr# find the outliers for each category
def outliers(group):cat = group.namereturn group[(group.score > upper.loc[cat]['score']) | (group.score < lower.loc[cat]['score'])]['score']
out = groups.apply(outliers).dropna()# prepare outlier data for plotting, we need coordinates for every outlier.
if not out.empty:outx = []outy = []for keys in out.index:outx.append(keys[0])outy.append(out.loc[keys[0]].loc[keys[1]])p = figure(tools="", background_fill_color="#efefef", x_range=cats, toolbar_location=None)# if no outliers, shrink lengths of stems to be no longer than the minimums or maximums
qmin = groups.quantile(q=0.00)
qmax = groups.quantile(q=1.00)
upper.score = [min([x,y]) for (x,y) in zip(list(qmax.loc[:,'score']),upper.score)]
lower.score = [max([x,y]) for (x,y) in zip(list(qmin.loc[:,'score']),lower.score)]# stems
p.segment(cats, upper.score, cats, q3.score, line_color="black")
p.segment(cats, lower.score, cats, q1.score, line_color="black")# boxes
p.vbar(cats, 0.7, q2.score, q3.score, fill_color="#E08E79", line_color="black")
p.vbar(cats, 0.7, q1.score, q2.score, fill_color="#3B8686", line_color="black")# whiskers (almost-0 height rects simpler than segments)
p.rect(cats, lower.score, 0.2, 0.01, line_color="black")
p.rect(cats, upper.score, 0.2, 0.01, line_color="black")# outliers
if not out.empty:p.circle(outx, outy, size=6, color="#F38630", fill_alpha=0.6)p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = "white"
p.grid.grid_line_width = 2
p.xaxis.major_label_text_font_size="16px"output_file("boxplot.html", title="boxplot.py example")show(p)

boxplot
  • burtin

from collections import OrderedDict
from io import StringIO
from math import log, sqrtimport numpy as np
import pandas as pdfrom bokeh.plotting import figure, output_file, showantibiotics = """
bacteria,                        penicillin, streptomycin, neomycin, gram
Mycobacterium tuberculosis,      800,        5,            2,        negative
Salmonella schottmuelleri,       10,         0.8,          0.09,     negative
Proteus vulgaris,                3,          0.1,          0.1,      negative
Klebsiella pneumoniae,           850,        1.2,          1,        negative
Brucella abortus,                1,          2,            0.02,     negative
Pseudomonas aeruginosa,          850,        2,            0.4,      negative
Escherichia coli,                100,        0.4,          0.1,      negative
Salmonella (Eberthella) typhosa, 1,          0.4,          0.008,    negative
Aerobacter aerogenes,            870,        1,            1.6,      negative
Brucella antracis,               0.001,      0.01,         0.007,    positive
Streptococcus fecalis,           1,          1,            0.1,      positive
Staphylococcus aureus,           0.03,       0.03,         0.001,    positive
Staphylococcus albus,            0.007,      0.1,          0.001,    positive
Streptococcus hemolyticus,       0.001,      14,           10,       positive
Streptococcus viridans,          0.005,      10,           40,       positive
Diplococcus pneumoniae,          0.005,      11,           10,       positive
"""drug_color = OrderedDict([("Penicillin",   "#0d3362"),("Streptomycin", "#c64737"),("Neomycin",     "black"  ),
])gram_color = OrderedDict([("negative", "#e69584"),("positive", "#aeaeb8"),
])df = pd.read_csv(StringIO(antibiotics),skiprows=1,skipinitialspace=True,engine='python')width = 800
height = 800
inner_radius = 90
outer_radius = 300 - 10minr = sqrt(log(.001 * 1E4))
maxr = sqrt(log(1000 * 1E4))
a = (outer_radius - inner_radius) / (minr - maxr)
b = inner_radius - a * maxrdef rad(mic):return a * np.sqrt(np.log(mic * 1E4)) + bbig_angle = 2.0 * np.pi / (len(df) + 1)
small_angle = big_angle / 7p = figure(plot_width=width, plot_height=height, title="",x_axis_type=None, y_axis_type=None,x_range=(-420, 420), y_range=(-420, 420),min_border=0, outline_line_color="black",background_fill_color="#f0e1d2")p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None# annular wedges
angles = np.pi/2 - big_angle/2 - df.index.to_series()*big_angle
colors = [gram_color[gram] for gram in df.gram]
p.annular_wedge(0, 0, inner_radius, outer_radius, -big_angle+angles, angles, color=colors,
)# small wedges
p.annular_wedge(0, 0, inner_radius, rad(df.penicillin),-big_angle+angles+5*small_angle, -big_angle+angles+6*small_angle,color=drug_color['Penicillin'])
p.annular_wedge(0, 0, inner_radius, rad(df.streptomycin),-big_angle+angles+3*small_angle, -big_angle+angles+4*small_angle,color=drug_color['Streptomycin'])
p.annular_wedge(0, 0, inner_radius, rad(df.neomycin),-big_angle+angles+1*small_angle, -big_angle+angles+2*small_angle,color=drug_color['Neomycin'])# circular axes and lables
labels = np.power(10.0, np.arange(-3, 4))
radii = a * np.sqrt(np.log(labels * 1E4)) + b
p.circle(0, 0, radius=radii, fill_color=None, line_color="white")
p.text(0, radii[:-1], [str(r) for r in labels[:-1]],text_font_size="11px", text_align="center", text_baseline="middle")# radial axes
p.annular_wedge(0, 0, inner_radius-10, outer_radius+10,-big_angle+angles, -big_angle+angles, color="black")# bacteria labels
xr = radii[0]*np.cos(np.array(-big_angle/2 + angles))
yr = radii[0]*np.sin(np.array(-big_angle/2 + angles))
label_angle=np.array(-big_angle/2+angles)
label_angle[label_angle < -np.pi/2] += np.pi # easier to read labels on the left side
p.text(xr, yr, df.bacteria, angle=label_angle,text_font_size="12px", text_align="center", text_baseline="middle")# OK, these hand drawn legends are pretty clunky, will be improved in future release
p.circle([-40, -40], [-370, -390], color=list(gram_color.values()), radius=5)
p.text([-30, -30], [-370, -390], text=["Gram-" + gr for gr in gram_color.keys()],text_font_size="9px", text_align="left", text_baseline="middle")p.rect([-40, -40, -40], [18, 0, -18], width=30, height=13,color=list(drug_color.values()))
p.text([-15, -15, -15], [18, 0, -18], text=list(drug_color),text_font_size="12px", text_align="left", text_baseline="middle")output_file("burtin.html", title="burtin.py example")show(p)

burtin

其他可视化作品我们直接放出结果,绘制代码省略,大家可自行去官网搜索哈:

  • periodic

periodic
  • markers

markers plots

以上所有的可视化作品都是可以交互操作的哦,除此之外,Bokeh 还提供大量的可视化APP应用,具体内容,感兴趣的小伙伴可自行搜索哈~~

总结

这一期我们分享了Python-Bokeh库绘制的可视化作品,体验了Python用于绘制交互式可视化作品放入方便性,还是那句话,适合自己的才是最好的,不要纠结所使用的工具哈,让我们一起探索数据可视化的魅力吧~~

参考来源:https://docs.bokeh.org/en/latest/docs/gallery.html

推荐阅读
Pandas处理数据太慢,来试试Polars吧!
懒人必备!只需一行代码,就能导入所有的Python库
绝!关于pip的15个使用小技巧
介绍10个常用的Python内置函数,99.99%的人都在用!
可能是全网最完整的 Python 操作 Excel库总结!

Bokeh,一个超强交互式Python可视化库!相关推荐

  1. Bokeh,一个超强交互式 Python 可视化库!

    这是「进击的Coder」的第 424 篇技术分享 作者:宁海涛 来源:DataCharm " 阅读本文大概需要 8 分钟. " 之前一直有小伙伴私信说让我多出些关于 Python ...

  2. 遇事不决,量子力学;不懂配色,赛博朋克。推荐一个Python可视化库

    遇事不决,量子力学;不懂配色,赛博朋克.推荐一个Python可视化库 12月10日,历经多次跳票后,波兰公司CD Projekt Red制作的<赛博朋克2077>终于正式发售,在Steam ...

  3. 新视角带你认识Python可视化库(附代码资源)

    作者:Dan Saber 翻译:笪洁琼 校对:梁傅淇 本文约16196字,建议阅读20+分钟. 本文中,作者借助拟人化的形式,让Python中值得一提的可视化库共同出演了一出戏剧,形象.生动地展现了不 ...

  4. Python 可视化库

    https://www.infoq.cn/article/pSV6tZ1SbUC8qJpo_v8H 在奥斯汀举行的SciPy 2018年特别会议上,大量开源 Python 可视化工具的代表分享了他们对 ...

  5. python三维数据转换成二维_5大Python可视化库到底选哪个好?一篇文章搞定从选库到教学...

    最近和鲸社区的大佬们,竟不约而同地写起了可视化库的教程,开始了掰头 ※完整教程列表在文末附录 虽然对于我们这种吃瓜群众来说是件好事,但 大概大佬的快乐往往就是那么的朴实无华且枯燥吧.害,管他呢,赶紧拿 ...

  6. python拿什么做可视化界面好_5大Python可视化库到底选哪个好?一篇文章搞定从选库到教学...

    最近和鲸社区的大佬们,不约而同地写起了可视化库的教程 虽然对于我们这种吃瓜群众来说是件好事,但 大概大佬的快乐往往就是那么的朴实无华且枯燥吧.害,管他呢,赶紧拿出来给大家瞅瞅. 今天提及的5个Pyth ...

  7. 【CSDN软件工程师能力认证学习精选】Python可视化库

    CSDN软件工程师能力认证(以下简称C系列认证)是由中国软件开发者网CSDN制定并推出的一个能力认证标准.C系列认证历经近一年的实际线下调研.考察.迭代.测试,并梳理出软件工程师开发过程中所需的各项技 ...

  8. python可视化库总结_Python 可视化库 - Matplotlib 使用总结

    Python 可视化库 - Matplotlib 使用总结 在做完数据分析后, 有时候需要将分析结果一目了然地展示出来, 此时便离不开 Python 可视化工具, Matplotlib 是 Pytho ...

  9. python修改文件名称唯美_5行代码搞定14种常见图的python可视化库,还自带16种优美主题,真是太喜欢了...

    原创:小dull鸟 python数据分析之禅 原文链接: 5行代码搞定14种常见图的python可视化库,还自带16种优美主题,真是太喜欢了​mp.weixin.qq.com 有时候我们做数据可视化并 ...

最新文章

  1. 软件工程实训有必要吗_人工智能专业值得读吗?就业如何?
  2. 数据库审计服务器性能要求,数据库审计技术指标资质要求-.docx
  3. java数据结构库函数_Java8 内置函数(api)总结
  4. 探秘IntelliJ IDEA 13测试版新功能——调试器显示本地变量
  5. 【转】内存耗用:VSS/RSS/PSS/USS
  6. Oracle入门(三A)之sqlplus
  7. java面试题7 牛客:关于AWT和Swing说法正确的是?
  8. 美国在理论计算机科学的研究重视,清华麻省理工香港中文联建理论计算机科学研究中心...
  9. mysql定义条件和处理_mysql sql存储过程条件定义与处理
  10. 设计模式速查手册-创建型
  11. LeetCode刷题(36)--Text Justification
  12. 【软件测试】如何用场景法进行黑盒测试
  13. 步步为营:因为数据库正在使用,所以无法获得对数据库的独占访问权
  14. live2d_原画人插画教程,想知道live2d虚拟主播是怎么制作出来的吗?
  15. 阿里云备案流程(终于去掉8080端口也能访问网站)
  16. boost format使用详解
  17. Linux下 vim的基本配置
  18. 6-3 选队长 (5 分)
  19. 韦伯望远镜拍摄图片震撼来袭!!
  20. 产品经理可以考哪些证书提升自己?一篇文章回答你

热门文章

  1. 网络中的七层协议与TCP/IP五层模型
  2. 反思不可佛系:刺激身体 刺激神经 目标反馈 定量奖惩 注重氛围
  3. Bootstrap的lia
  4. 12v电量显示制作方法_如何制作老式12v充电器(四款12v充电器设计制作详解)
  5. PHP面向对象基础总结
  6. 计算机故障的分析原理,蓝屏含义、原理分析、处理方法 电脑计算机故障系统安全...
  7. mysql 字符串替换:处理历史稿件中的图片路径
  8. java.lang.NoClassDefFoundError comfasterxmljacksonannotationJsonView
  9. 计算机思维能力培养的核心是什么,计算机基础教学的核心任务是计算思维能力的培养[J]...
  10. oracle u4e00 u9fa5,oracle中文与数字正则实例代码