You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Vispy高效创建大量矩形以实现条形图?

嘿,这个问题我之前做大数据可视化时也踩过坑!循环创建单个Rectangle确实会因为生成太多独立的可视化对象直接拖垮性能——每个Rectangle都要单独创建自己的顶点缓冲和渲染状态,GPU每次都得单独处理,数量过百之后性能暴跌太正常了。

其实Vispy早就为这种场景准备了更高效的解决方案,直接用内置的**BarGraph组件**就好,完全是为批量绘制条形图量身打造的,不用再手动拼单个矩形:

修改后的完整代码

import sys
import numpy as np
from vispy import scene, app

canvas = scene.SceneCanvas(keys='interactive')
canvas.size = 600, 600
canvas.show()

grid = canvas.central_widget.add_grid()
view = grid.add_view(row=0, col=0)
view.camera = scene.PanZoomCamera(rect=(-1,-1,10,10))

# 用BarGraph一次性创建所有条形
x_positions = np.arange(10)  # 每个条形的中心x坐标
heights = np.arange(10)      # 每个条形的高度(和你原来的i对应)
widths = np.full(10, 0.5)    # 所有条形的宽度统一为0.5
colors = ['r'] * 10          # 可以自定义每个条形的颜色,比如np.random.rand(10,4)生成随机色

bar_graph = scene.visuals.BarGraph(
    x=x_positions,
    height=heights,
    width=widths,
    color=colors,
    parent=view.scene
)

gl = scene.visuals.GridLines(parent=view.scene)

if __name__ == '__main__' and sys.flags.interactive == 0:
    app.run()

为什么这样性能好?

BarGraph内部会把所有条形的顶点数据打包成单个顶点缓冲对象(VBO),GPU只需要一次绘制调用就能渲染所有条形,哪怕是上万条数据也能轻松扛住,完全不会有循环创建单个矩形的性能问题。

如果你一定要用Rectangle实现批量绘制

要是你因为特殊需求必须基于Rectangle类来做,也可以直接用底层的vispy.visuals.RectangleVisual,传入数组类型的参数,让单个Visual对象批量渲染多个矩形:

from vispy.visuals import RectangleVisual

# 准备批量参数的数组
centers = np.column_stack((np.arange(10), np.arange(10)))  # 每个矩形的中心坐标,shape(10,2)
heights = np.full(10, 1)
widths = np.full(10, 0.5)
colors = np.tile([1, 0, 0, 1], (10, 1))  # 红色,RGBA格式

# 单个RectangleVisual就能渲染所有矩形
batch_rects = RectangleVisual(
    center=centers,
    height=heights,
    width=widths,
    color=colors
)
view.add(batch_rects)

不过还是优先推荐BarGraph,它已经封装了条形图的常用功能,比手动处理Rectangle省心多啦~

内容的提问来源于stack exchange,提问作者progS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:38:21