danijar
danijar

Reputation: 34175

How to set markers only at tick positions in matplotlib?

I am aware of the markevery option that allows to only place a marker at every n-th point. However, I'm using the MaxNLocator to define tick positions and would like to display markers at those tick positions only. How can I display markers at tick positions only, either using an option or manually placing them?

Upvotes: 1

Views: 1022

Answers (1)

pathoren
pathoren

Reputation: 1666

You can get the ticks with ax.get_xticks(), find the closest point corresponding to each xtick and then get the index to the x-values. With the indices it is easy to plot the xtick-values.

#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')

def find_nearest(array,value):
    idx = (np.abs(array-value)).argmin()
    return idx

x = np.linspace(-1, 1, 100)
y = x**2

fig, ax = plt.subplots(1, 1)

ax.plot(x, y, '--')

xtick = ax.get_xticks()

idx = [find_nearest(x, tick) for tick in xtick]

ax.plot(x[idx], y[idx], 'ro')

plt.show()  

Upvotes: 2

Related Questions