Python可视化库之HoloViews的使用教程

作者:Python学习与数据挖掘 时间:2023-11-05 17:09:03 

最近一直在整理统计图表的绘制方法,发现Python中除了经典Seaborn库外,还有一些优秀的可交互的第三方库也能实现一些常见的统计图表绘制,而且其还拥有Matplotlib、Seaborn等库所不具备的交互效果。

当然,同时也能绘制出版级别的图表要求,此外,一些在使用Matplotlib需自定义函数才能绘制的图表在一些第三方库中都集成了,这也大大缩短了绘图时间。

今天我就详细介绍一个优秀的第三方库-HoloViews,内容主要如下:

  • Python-HoloViews库介绍

  • Python-HoloViews库样例介绍

Python-HoloViews库介绍

Python-HoloViews库作为一个开源的可视化库,其目的是使数据分析结果和可视化完美衔接,其默认的绘图主题和配色以及较少的绘图代码量,可以使你专注于数据分析本身,同时其统计绘图功能也非常优秀。更多关于HoloViews库的介绍,可参考:Python-HoloViews库官网[1]

Python-HoloViews库样例介绍

这一部分小编重点放在一些统计图表上,其绘制结果不仅可以在网页上交互,同时其默认的绘图结果也完全满足出版界别的要求,主要内容如下(以下图表都是可交互的):

密度图+箱线图

import pandas as pd
import holoviews as hv
from bokeh.sampledata import autompg

hv.extension('bokeh')
df = autompg.autompg_clean
bw = hv.BoxWhisker(df, kdims=["origin"], vdims=["mpg"])
dist = hv.NdOverlay(
   {origin: hv.Distribution(group, kdims=["mpg"])
        for origin, group in df.groupby("origin")}
)

bw + dist

Python可视化库之HoloViews的使用教程

密度图+箱线图

散点图+横线图

scatter = hv.Scatter(df, kdims=["origin"], vdims=["mpg"]).opts(jitter=0.3)

yticks = [(i + 0.25, origin) for i, origin in enumerate(df["origin"].unique())]
spikes = hv.NdOverlay(
   {
       origin: hv.Spikes(group["mpg"]).opts(position=i)
           for i, (origin, group) in enumerate(df.groupby("origin", sort=False))
   }
).opts(hv.opts.Spikes(spike_length=0.5, yticks=yticks, show_legend=False, alpha=0.3))

scatter + spikes

Python可视化库之HoloViews的使用教程

散点图+横线图

Iris Splom

from bokeh.sampledata.iris import flowers
from holoviews.operation import gridmatrix

ds = hv.Dataset(flowers)

grouped_by_species = ds.groupby('species', container_type=hv.NdOverlay)
grid = gridmatrix(grouped_by_species, diagonal_type=hv.Scatter)
grid.opts(opts.Scatter(tools=['hover', 'box_select'], bgcolor='#efe8e2', fill_alpha=0.2, size=4))

Python可视化库之HoloViews的使用教程

Iris Splom

面积图

# create some example data
python=np.array([2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111])
pypy=np.array([12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130])
jython=np.array([22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160])

dims = dict(kdims='time', vdims='memory')
python = hv.Area(python, label='python', **dims)
pypy   = hv.Area(pypy,   label='pypy',   **dims)
jython = hv.Area(jython, label='jython', **dims)

opts.defaults(opts.Area(fill_alpha=0.5))
overlay = (python * pypy * jython)
overlay.relabel("Area Chart") + hv.Area.stack(overlay).relabel("Stacked Area Chart")

Python可视化库之HoloViews的使用教程

面积图

直方图系列

def get_overlay(hist, x, pdf, cdf, label):
   pdf = hv.Curve((x, pdf), label='PDF')
   cdf = hv.Curve((x, cdf), label='CDF')
   return (hv.Histogram(hist, vdims='P(r)') * pdf * cdf).relabel(label)

np.seterr(divide='ignore', invalid='ignore')

label = "Normal Distribution (μ=0, σ=0.5)"
mu, sigma = 0, 0.5

measured = np.random.normal(mu, sigma, 1000)
hist = np.histogram(measured, density=True, bins=50)

x = np.linspace(-2, 2, 1000)
pdf = 1/(sigma * np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2 / (2*sigma**2))
cdf = (1+scipy.special.erf((x-mu)/np.sqrt(2*sigma**2)))/2
norm = get_overlay(hist, x, pdf, cdf, label)

label = "Log Normal Distribution (μ=0, σ=0.5)"
mu, sigma = 0, 0.5

measured = np.random.lognormal(mu, sigma, 1000)
hist = np.histogram(measured, density=True, bins=50)

x = np.linspace(0, 8.0, 1000)
pdf = 1/(x* sigma * np.sqrt(2*np.pi)) * np.exp(-(np.log(x)-mu)**2 / (2*sigma**2))
cdf = (1+scipy.special.erf((np.log(x)-mu)/(np.sqrt(2)*sigma)))/2
lognorm = get_overlay(hist, x, pdf, cdf, label)

label = "Gamma Distribution (k=1, θ=2)"
k, theta = 1.0, 2.0

measured = np.random.gamma(k, theta, 1000)
hist = np.histogram(measured, density=True, bins=50)

x = np.linspace(0, 20.0, 1000)
pdf = x**(k-1) * np.exp(-x/theta) / (theta**k * scipy.special.gamma(k))
cdf = scipy.special.gammainc(k, x/theta) / scipy.special.gamma(k)
gamma = get_overlay(hist, x, pdf, cdf, label)

label = "Beta Distribution (α=2, β=2)"
alpha, beta = 2.0, 2.0

measured = np.random.beta(alpha, beta, 1000)
hist = np.histogram(measured, density=True, bins=50)

x = np.linspace(0, 1, 1000)
pdf = x**(alpha-1) * (1-x)**(beta-1) / scipy.special.beta(alpha, beta)
cdf = scipy.special.btdtr(alpha, beta, x)
beta = get_overlay(hist, x, pdf, cdf, label)

label = "Weibull Distribution (λ=1, k=1.25)"
lam, k = 1, 1.25

measured = lam*(-np.log(np.random.uniform(0, 1, 1000)))**(1/k)
hist = np.histogram(measured, density=True, bins=50)

x = np.linspace(0, 8, 1000)
pdf = (k/lam)*(x/lam)**(k-1) * np.exp(-(x/lam)**k)
cdf = 1 - np.exp(-(x/lam)**k)
weibull = get_overlay(hist, x, pdf, cdf, label)

Python可视化库之HoloViews的使用教程

直方图系列

Route Chord

import holoviews as hv
from holoviews import opts, dim
from bokeh.sampledata.airport_routes import routes, airports

hv.extension('bokeh')

# Count the routes between Airports
route_counts = routes.groupby(['SourceID', 'DestinationID']).Stops.count().reset_index()
nodes = hv.Dataset(airports, 'AirportID', 'City')
chord = hv.Chord((route_counts, nodes), ['SourceID', 'DestinationID'], ['Stops'])

# Select the 20 busiest airports
busiest = list(routes.groupby('SourceID').count().sort_values('Stops').iloc[-20:].index.values)
busiest_airports = chord.select(AirportID=busiest, selection_mode='nodes')
busiest_airports.opts(
   opts.Chord(cmap='Category20', edge_color=dim('SourceID').str(),
              height=800, labels='City', node_color=dim('AirportID').str(), width=800))

Python可视化库之HoloViews的使用教程

Route Chord

小提琴图

import holoviews as hv
from holoviews import dim

from  bokeh.sampledata.autompg import autompg
hv.extension('bokeh')

violin = hv.Violin(autompg, ('yr', 'Year'), ('mpg', 'Miles per Gallon')).redim.range(mpg=(8, 45))
violin.opts(height=500, width=900, violin_fill_color=dim('Year').str(), cmap='Set1')

Python可视化库之HoloViews的使用教程

小提琴图

更多样例可查看:Python-HoloViews样例[2]

来源:https://blog.csdn.net/weixin_38037405/article/details/123060349

标签:Python,可视化,HoloViews
0
投稿

猜你喜欢

  • Python设计模式中的创建型工厂模式

    2023-05-09 17:47:02
  • python输出100以内的质数与合数实例代码

    2021-01-30 20:47:52
  • 解读Python中字典的key都可以是什么

    2023-09-23 05:29:37
  • JavaScript中变量、指针和引用功能与操作示例

    2024-04-17 10:07:16
  • oracle 集合

    2009-06-19 18:09:00
  • python正则表达式匹配IP代码实例

    2022-01-03 00:25:52
  • itchat-python搭建微信机器人(附示例)

    2022-05-04 00:00:54
  • MySQL触发器的使用场景及方法实例

    2024-01-23 04:45:12
  • python中redis的安装和使用

    2021-02-21 23:19:44
  • SQL LOADER错误小结

    2024-01-20 23:26:36
  • js实现做通讯录的索引滑动显示效果和滑动显示锚点效果

    2024-04-16 09:23:00
  • python测试开发django之使用supervisord 后台启动celery 服务(worker/beat)

    2023-10-14 05:55:53
  • python使用xlrd实现检索excel中某列含有指定字符串记录的方法

    2021-04-23 12:41:26
  • SQL Server中使用SQL语句实现把重复行数据合并为一行并用逗号分隔

    2024-01-18 03:06:54
  • 一小时快速入门Python教程

    2023-03-06 04:07:03
  • JavaScript面试必考之实现手写Promise

    2024-04-16 10:38:49
  • ASP 读取MP3文件帧的信息比特率,采样频率,播放时间

    2010-06-04 12:22:00
  • python 多线程中join()的作用

    2022-11-27 12:24:24
  • python实现读取大文件并逐行写入另外一个文件

    2021-02-03 21:10:45
  • MySQL datetime类型与时间、日期格式字符串大小比较的方法

    2024-01-25 23:25:24
  • asp之家 网络编程 m.aspxhome.com