Skip to content
Advertisement

Drawing a closed loop with Altair mark_line without repeating data

See this example and this similar question. I also want to draw a closed loop with mark_line in Altair. However, I am currently in the process of streamlining my code to be more data-efficient, which is presenting a wrinkle that I am having trouble with.

I have a dataset of x and y data that I plot as a scatterplot. Then I have a list of point indexes that I want to connect with a line that closes back on itself. I previously accomplished this by performing a .loc[] on the indexes to create a new dataframe and using mark_line with order=False. However, this increases the size of my plot because the returned .loc[] dataframe is stored in the spec as a second data object, repeating the data in the main dataset.

I think the “correct” way to draw this line without defining a new dataframe is to create a new column to use as the order parameter and use a transform_filter to reduce to only the relevant indexes. However, this then leaves my line one segment short because I can’t return to the start without repeating the entire row (as I do in the .loc[] solution).

Is there any way to close this line without creating a new data object? I would also prefer not to add duplicate rows to the starting dataframe since that is being used to render the full scatterplot (and some other plot objects) as well. My best thought right now is to use a second mark_line but this time with a transform_filter that only includes the first/last indexes, but that seems kludgy.

The following code shows the example old way / new way I have been using for this, on a much smaller dataset (where the efficiency doesn’t really matter).

JavaScript

Plot_v1 output: plot_v1 output

Plot_v2 output: plot_v2 output

Advertisement

Answer

You can use .mark_line(interpolate='linear-closed') to form a polygon in your plot_v2 example. More info on different interpolation modes can be found in the docs.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement