Matplotlib Indicate Point On X And Y Axis
I often want to highlight a point along a curve using matplotlib to make a plot that looks like: The following code was used to create the plot import numpy as np import matplotli
Solution 1:
A way to go could be to update the lines each time the canvas gets redrawn. To this end we could create a class PointMarkers
with an update method that is connected to the draw_event
listener. This way the lines will update not only if points are added after the marker lines' creation, but also when the canvas is resized or panned.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
classPointMarker():
def__init__(self, ax, point, **kwargs):
self.ax = ax
self.point = point
if"line"in kwargs:
self.c = kwargs.get("line").get_color()
else:
self.c = kwargs.get("color", "b")
self.ls=kwargs.get("linestyle", ':')
self.vline, = self.ax.plot([],[],color=self.c,linestyle=self.ls)
self.hline, = self.ax.plot([],[],color=self.c,linestyle=self.ls)
self.draw()
defdraw(self):
xmin = ax.get_xlim()[0]
ymin = ax.get_ylim()[0]
self.vline.set_data([self.point[0], self.point[0]], [ymin,self.point[1]])
self.hline.set_data([xmin, self.point[0]], [self.point[1], self.point[1]])
classPointMarkers():
pointmarkers = []
defadd(self,ax, point, **kwargs ):
pm = PointMarker(ax, point, **kwargs)
self.pointmarkers.append(pm)
defupdate(self, event=None):
for pm in self.pointmarkers:
pm.draw()
x = np.arange(1,17)
y = np.log(x)
ax = plt.subplot(111)
line = plt.plot(x,y)
# register the markers
p = PointMarkers()
p.add(ax,[x[5],y[5]], line=line[0])
p.add(ax,[x[12],y[12]], color="purple", linestyle="-.")
# connect event listener
cid = plt.gcf().canvas.mpl_connect("draw_event", p.update)
#testing: draw some new points or change axis limits
plt.plot([5,11],[-0.5,0.6])
#plt.xlim([0,85])#plt.ylim([0,1])
plt.show()
For saving, the redrawing would need to be performed manually directly before the save command, like
plt.gcf().canvas.draw()
plt.savefig(...)
Post a Comment for "Matplotlib Indicate Point On X And Y Axis"