Skip to content

Multiple add_plot calls connect disconnected line segments #47

@krystophny

Description

@krystophny

Description

When calling fig%add_plot() multiple times in a loop to draw disconnected line segments (e.g., for plotting mesh triangles), fortplotlib appears to connect the last point of one plot to the first point of the next plot, creating spurious connections.

Minimal Reproducible Example

program test_disconnected_lines
    use fortplot
    use fortplot_figure, only: figure_t
    implicit none
    
    type(figure_t) :: fig
    real(8) :: x_line(2), y_line(2)
    
    call fig%initialize()
    
    \! Plot first line segment: (0,0) to (1,0)
    x_line = [0.0_8, 1.0_8]
    y_line = [0.0_8, 0.0_8]
    call fig%add_plot(x_line, y_line)
    
    \! Plot second line segment: (2,1) to (3,1)
    x_line = [2.0_8, 3.0_8]
    y_line = [1.0_8, 1.0_8]
    call fig%add_plot(x_line, y_line)
    
    call fig%savefig("disconnected_lines.png")
end program

Expected Behavior

The plot should show two separate horizontal line segments:

  • One from (0,0) to (1,0)
  • One from (2,1) to (3,1)

Actual Behavior

The plot shows the two line segments connected by an additional line from (1,0) to (2,1).

Use Case

This issue was discovered when trying to plot mesh triangles in FortFEM. Each triangle needs to be drawn as a closed path, but when plotting multiple triangles in a loop, fortplotlib connects the triangles together.

Workaround

Currently, the workaround is to plot each edge separately:

\! Instead of plotting closed triangles
do i = 1, n_triangles
    \! Get triangle vertices...
    x_triangle = [x1, x2, x3, x1]  \! Closed path
    y_triangle = [y1, y2, y3, y1]
    call fig%add_plot(x_triangle, y_triangle)  \! This connects triangles
end do

\! Plot each edge separately
do i = 1, n_triangles
    \! Edge 1
    x_edge = [x1, x2]
    y_edge = [y1, y2]
    call fig%add_plot(x_edge, y_edge)
    \! Edge 2...
    \! Edge 3...
end do

Suggested Solutions

  1. Add a parameter to add_plot to indicate disconnected segments:

    call fig%add_plot(x, y, connected=.false.)
  2. Support NaN values as line breaks (like matplotlib):

    x = [0.0, 1.0, NaN, 2.0, 3.0]
    y = [0.0, 0.0, NaN, 1.0, 1.0]
    call fig%add_plot(x, y)
  3. Add a method to explicitly break the line:

    call fig%add_plot(x1, y1)
    call fig%break_line()
    call fig%add_plot(x2, y2)

Environment

  • fortplotlib version: latest from GitHub
  • Context: Used in FortFEM finite element library for mesh visualization

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions