Skip to content
Advertisement

Align matplotlib scatter marker left and or right

I am using the matplotlib scatterplot function to create the appearance of handles on vertical lines to delineate certain parts of a graph. However, in order to make them look correct, I need to be able to align the scatter plot marker to the left (for the left line / delineator) and / or right (for the right line / delineator).

Here’s an example:

JavaScript

The code above gives me almost the graph I’m looking for, like this:

focus_timeline

However, I’d like the leftmost marker (“>”) to be “aligned left” (i.e. shifted slightly to the right) so that the line is continued to the back of the marker Likewise, I’d like the rightmost marker (“<“) to be “aligned right” (i.e. slightly shifted to the left). Like this:

desired_fig

Any guidance or suggestions on how to accomplish this in a flexible manner?

NOTE: In practice, my DataFrame index is pandas.Datetime not integers as I’ve provided for this simple example.

Advertisement

Answer

I liked this question and was not satisfied with my first answer. In particular, it seemed unnecessarily cumbersome to create figure specific objects (mark_align_*) in order to align markers. What I eventually found was the functionality to specify a marker by verts (a list of 2-element floats, or an Nx2 array, that specifies the marker vertices relative to the target plot-point at (0, 0)). To utilize this functionality for this purpose I wrote this function,

JavaScript

Using this function, the desired markers can be plotted as,

JavaScript

or using ax.scatter,

JavaScript

In both of these examples I have specified transform=ax.get_xaxis_transform() so that the vertical position of the markers is in axes coordinates (1 is the top of the axes), this has nothing to do with the marker alignment.

The obvious advantage of this solution compared to my previous one is that it does not require knowledge of the markersize, plotting function (ax.plot vs. ax.scatter), or axes (for the transform). Instead, one simply specifes a marker and its alignment!

Cheers!

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