Skip to content

Recalculate ChartXY plot bounds when plot data is modified

dcbr requested to merge dcbr/vtk:chart_xy_update into master

When a plot is added or removed from a ChartXY, the RecalculateBounds method is called such that the chart's axes are automatically rescaled (when the axis behaviour is AUTO). This is however not done when a plot is modified. This MR also calls RecalculateBounds in those situations.

Python code to reproduce below results
import vtk

def create_xy_chart():
    data = [(1, 2), (2, 0), (3, 1)]
    chart = vtk.vtkChartXY()

    table = vtk.vtkTable()
    arrX = vtk.vtkFloatArray()
    arrX.SetName(f"X")
    arrY = vtk.vtkFloatArray()
    arrY.SetName(f"Y")
    table.AddColumn(arrX)
    table.AddColumn(arrY)

    numPoints = len(data)
    table.SetNumberOfRows(numPoints)
    for p in range(numPoints):
        table.SetValue(p, 0, data[p][0])
        table.SetValue(p, 1, data[p][1])

    plot = chart.AddPlot(vtk.vtkChart.POINTS)
    plot.SetInputData(table, 0, 1)

    axis = chart.GetAxis(vtk.vtkAxis.BOTTOM)
    axis.SetBehavior(vtk.vtkAxis.FIXED)
    axis.SetRange(0, 5)

    return chart, table, axis


if __name__ == "__main__":
    update = "plot"
    renwin = vtk.vtkRenderWindow()
    renwin.SetSize(400, 400)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)

    renderer = vtk.vtkRenderer()
    renderer.SetBackground([1, 1, 1])
    renwin.AddRenderer(renderer)

    chart_scene = vtk.vtkContextScene()
    chart_actor = vtk.vtkContextActor()
    chart_actor.SetScene(chart_scene)
    renderer.AddActor(chart_actor)
    chart_scene.SetRenderer(renderer)

    chart, table, axis = create_xy_chart()
    chart_scene.AddItem(chart)

    style = vtk.vtkContextInteractorStyle()
    style.SetScene(chart_scene)
    iren.SetInteractorStyle(style)
    renwin.Render()
    iren.Start()

    if update == "plot":
        # Update plot's data table
        table.SetValue(2, 0, 5)
        table.SetValue(2, 1, 3)
        table.Modified()
    elif update == "axis":
        # Update axis range
        axis.SetBehavior(vtk.vtkAxis.AUTO)
    renwin.Render()
    iren.Start()

Above code generates an initial chart with three datapoints and a fixed X axis range that looks as follows.

Initial plot (identical before & after MR)
image

It then either modifies the plot data or modifies the X axis behavior to AUTO. Results are summarized in the table below.

Update Before After
"plot" image image
"axis" image image

Update: The "axis" changes are more tricky and I'll try to address them in a separate MR.

Edited by dcbr

Merge request reports

Loading