Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Visual: Bar #2394

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
45 changes: 45 additions & 0 deletions examples/scene/bar_plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
# vispy: gallery 2
# -----------------------------------------------------------------------------
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
"""
Vertical bar plot with Axis
===========================
"""

import numpy as np
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example will need a docstring like the other examples in this gallery directory. Formatting and content is important since it appears in the final website.

from vispy import scene, app

if __name__ == "__main__":

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

grid = canvas.central_widget.add_grid()
grid.padding = 10

vb1 = grid.add_view(row=0, col=1, camera='panzoom')

x_axis1 = scene.AxisWidget(orientation='bottom')
x_axis1.stretch = (1, 0.1)
grid.add_widget(x_axis1, row=1, col=1)
x_axis1.link_view(vb1)
y_axis1 = scene.AxisWidget(orientation='left')
y_axis1.stretch = (0.1, 1)
grid.add_widget(y_axis1, row=0, col=0)
y_axis1.link_view(vb1)

grid_lines1 = scene.visuals.GridLines(parent=vb1.scene)

color_array = np.array([[1,0,0], [0,1,0], [0, 0, 1], [0.5, 1, 0.25], [1, 0.5, 0.25], [0.25, 0.5, 1], [1,0,0], [0,1,0], [0, 0, 1], [0.5, 1, 0.25], [1, 0.5, 0.25], [0.25, 0.5, 1]])

bar1 = scene.Bar(height=np.arange(0, 6, 0.5), # for a more traditional horizontal plot, either remove the
bottom=np.arange(0, 3, 0.25), width=0.8, shift=0.5, # orientation paramenter outright
orientation='v', color=color_array, parent=vb1.scene) # or set it to 'h'

vb1.camera.set_range()

app.run()
1 change: 1 addition & 0 deletions vispy/scene/visuals.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ def generate_docstring(subclass, clsname):

Arrow = create_visual_node(visuals.ArrowVisual)
Axis = create_visual_node(visuals.AxisVisual)
Bar = create_visual_node(visuals.BarVisual)
Box = create_visual_node(visuals.BoxVisual)
ColorBar = create_visual_node(visuals.ColorBarVisual)
Compound = create_visual_node(visuals.CompoundVisual)
Expand Down
1 change: 1 addition & 0 deletions vispy/visuals/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"""

from .axis import AxisVisual # noqa
from .bar import BarVisual # noqa
from .box import BoxVisual # noqa
from .cube import CubeVisual # noqa
from .ellipse import EllipseVisual # noqa
Expand Down
132 changes: 132 additions & 0 deletions vispy/visuals/bar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------

import numpy as np

from vispy.color.color_array import ColorArray
from .mesh import MeshVisual


class BarVisual(MeshVisual):
"""Visual that calculates and displays a bar graph

Parameters
----------
data : array-like
1st column is the height, optional 2nd column is bottom
height : array-like
Height of the bars
bottom : array-like
Bottom of the bars
width : int | float
Width of all bars
shift : int | float
Shift of all bars along the x-axis
color : ColorArray | numpy.ndarray | str
Color of the bars or you can pass a 2d array with rgb values for each individual bar
orientation : {'h', 'v'}
Orientation of the bars - 'v' is default
'v' : |
'h' : -
color_array : array-like
[[1, 0, 0], [0, 1, 0], [0, 0, 1]] exactly one rgb array for each bar. This would be for 3 Bars
"""

def __init__(self, height, bottom=None, width=0.8, shift=0.0, color='w', orientation='v'):
if bottom is None:
bottom = np.zeros(height.shape[0])

if height.shape != bottom.shape:
raise ValueError("Height and Bottom must be same shape: Height: " + height.shape + " Bottom: "
+ bottom.shape)

color_array = None

if isinstance(color, np.ndarray):
if len(color.shape) == 2:
if color.shape[1] == 3:
if color.shape[0] > 1 and color.shape[0] != 0:
color_array = np.repeat(color, 2, axis=0)
color = None
else:
raise ValueError('If you pass an numpy array as color it needs to be rgb i.e. 3 columns')
elif isinstance(color, ColorArray):
pass
elif isinstance(color, str):
pass
else:
raise ValueError("Color has to be either a vispy ColorArray, numpy array or a string for example: 'w'")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, maybe I wasn't very clear: using the ColorArray is specifically to get rid of all this extra logic (and unnecessary restrictions like passing only rgb). You can do this:

Suggested change
color_array = None
if isinstance(color, np.ndarray):
if len(color.shape) == 2:
if color.shape[1] == 3:
if color.shape[0] > 1 and color.shape[0] != 0:
color_array = np.repeat(color, 2, axis=0)
color = None
else:
raise ValueError('If you pass an numpy array as color it needs to be rgb i.e. 3 columns')
elif isinstance(color, ColorArray):
pass
elif isinstance(color, str):
pass
else:
raise ValueError("Color has to be either a vispy ColorArray, numpy array or a string for example: 'w'")
color = ColorArray(color).rgba
if len(color_array):
color = color_array[0]
color_array = None
else:
color = None

and then later

MeshVisual.set_data(self, rr, tris, color=color, face_colors=color_array)

Copy link
Contributor Author

@Bliss3d Bliss3d Oct 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how this is supposed to work, color_array is not defiened in that context

Copy link
Collaborator

@brisvag brisvag Oct 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry, wrote that in a rush. Fixed:

        color = ColorArray(color).rgba
        if len(color):
        	  color = color[0]
            color_array = None
        else:
            color = None
			  color_array = color

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I modified it a bit, but I hope it works for you


rr, tris = calc_vertices(height, bottom, width, shift, orientation)

MeshVisual.__init__(self, rr, tris, color=color, face_colors=color_array)

def update_data(self, height, bottom=None, width=0.8, shift=0.0, color='w', orientation='v', color_array=None):
if bottom is None:
bottom = np.zeros(height.shape[0])

if height.shape != bottom.shape:
raise ValueError("Height and Bottom must be same shape: Height: " + height.shape + " Bottom: "
+ bottom.shape)

color_array = None

if isinstance(color, np.ndarray):
if len(color.shape) == 2:
if color.shape[1] == 3:
if color.shape[0] > 1 and color.shape[0] != 0:
color_array = np.repeat(color, 2, axis=0)
color = None
else:
raise ValueError('If you pass an numpy array as color it needs to be rgb i.e. 3 columns')
elif isinstance(color, ColorArray):
pass
elif isinstance(color, str):
pass
else:
raise ValueError("Color has to be either a vispy ColorArray, numpy array or a string for example: 'w'")

rr, tris = calc_vertices(height, bottom, width, shift, orientation)

MeshVisual.set_data(self, rr, tris, color=color, face_colors=color_array)


def calc_vertices(height, bottom, width, shift, orientation):

y_position = np.zeros((height.shape[0], 2))

y_position[:, 0] = height
y_position[:, 1] = bottom

y_position = y_position.flatten().repeat(2)

stack_n_x2 = np.arange(height.shape[0]).repeat(2).reshape(-1, 1)

vertices = np.array([
[-width/2 + shift, 1],
[width/2 + shift, 1],
[width/2 + shift, 0],
[-width/2 + shift, 0]])

vertices = np.tile(vertices, (height.shape[0], 1))

if orientation == 'v':
vertices[:, 0] = vertices[:, 0] + stack_n_x2[:, 0].repeat(2)
vertices[:, 1] = y_position

elif orientation == 'h':
vertices[:, 1] = vertices[:, 0] + stack_n_x2[:, 0].repeat(2)
vertices[:, 0] = y_position
else:
raise ValueError('orientation can only be v (vertical) or h (horizontal). You specified: ' + str(orientation))

base_faces = np.array([[0, 1, 2], [0, 2, 3]])

base_faces = np.tile(base_faces, (height.shape[0], 1))

faces = stack_n_x2 * 4 + base_faces

return vertices, faces