Biggzlar
Biggzlar

Reputation: 43

How to invert the direction of a single axis tick in matplotlib?

I'd like to invert the direction of a single axis tick (and its label) along the x-axis to highlight some specified value.

I was successful in manipulating other attributes but apparently inverting the direction of a single tick is not so easily done. Here is my failed attempt at inverting the tick direction. Note that all other attributes apply as expected:

import numpy as np
import matplotlib.pyplot as plt


fig, ax = plt.subplots()

ax.plot(np.linspace(0, 1, 10), np.linspace(0, 1, 10))
ax.tick_params(axis="x", direction="out")

ticks = ax.xaxis.get_major_ticks()
ticks[2]._apply_params(direction="in", color="r", width=22)

plt.show()

Desired outcome: enter image description here

Upvotes: 2

Views: 76

Answers (2)

RuthC
RuthC

Reputation: 3777

You could use a secondary axis to draw the tick separately.

import numpy as np
import matplotlib.pyplot as plt


fig, ax = plt.subplots()

ax.plot(np.linspace(0, 1, 10), np.linspace(0, 1, 10))
ax.tick_params(axis="x", direction="out")

ax.xaxis.set_ticks([0, 0.4, 0.6, 0.8, 1])

secax = ax.secondary_xaxis('bottom')
secax.set_ticks([0.2])
secax.tick_params(direction='in', pad=-20, labelcolor='red')

plt.show()

enter image description here

Upvotes: 1

Guy
Guy

Reputation: 50799

You can set label1 attributes

ticks = ax.xaxis.get_major_ticks()
ticks[2].label1.set_y(0.1)
ticks[2].label1.set_color("r")

enter image description here

Upvotes: 0

Related Questions