Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlob: Plot open interval, connect line to empty circle [duplicate]

I would like to plot a line that ends in an empty circle. Essentially a visualization of the open interval [0, 1) My attempt is:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 20)
y = 1 + x*2
l, = plt.plot(x[:-1], y[:-1])
plt.scatter(x[-1], y[-1], marker='o', facecolor='none', edgecolor=l.get_color())

Unfortunately, the line does not connect to the circle. Alternatively, I can plot all of plt.plot(x, y), but then the line is inside the circle. What is a nice way of plotting it such that the line touches exactly the circle and does not go further?

I'm looking for an approach that allows me to reproduce this for other lines and does not require a lot of fine-tuning for each use case.

like image 486
FooBar Avatar asked May 12 '26 18:05

FooBar


1 Answers

A trick here is that plotting with a white background and raising the z order will plot the circle above the line:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 20)
y = 1 + x*2

l, = plt.plot(x, y)  # Change: plot whole series
plt.scatter(
    x[-1], y[-1], marker='o', 
    facecolor='white',  # Change: to opaque color
    edgecolor=l.get_color(),  
    linewidth=l.get_linewidth(),  # Change: match line width
    zorder=10  # Change: raise to higher level.
)

Another solution is to use the newer markevery options to specify where markers go as a list. This way we can use a single plot call:

plt.plot(x, y, 'o', 
         linestyle='-', 
         markevery=[-1], 
         markerfacecolor='white', 
         markeredgewidth=1.5)

Result:

result

like image 186
chthonicdaemon Avatar answered May 15 '26 08:05

chthonicdaemon