Python Matplot Y Axis Negative to Positive Label Range

Viewed 844

I'm trying to create y axis labels in a sequence of -20 to + 20 with 5 integer increments. I've tried this below with my plot axis = ax2:

ax2.set_yticks(list(range(-20, 25, 5)))
ax2.set_yticklabels([abs(y) for y in list(range(-20, 25, 5))])

and I get a y axis ranging from 20 to 20 that looks like this figure below:

figure from my program that needs new axis labels (negative numbers)

I need the y axis labels to list on the figure as: -20, -15, -10, -5, 0, 5, 10, 15, 20 and I've yet to find a solution online. Thank you for any help here!

2 Answers

You are using abs which always returns a positive number. Therefore, you don't see negative ticklabels. Moreover, you don't need list comprehension and neither do you need to convert range to list. You can also just use a variable rather than calling range() twice.

Just remove the abs and pass the range directly. In fact, for your current example, you don't even need to set y-ticklabels. Just setting the ticks would be sufficient.

For example:

fig, ax2 = plt.subplots()

ytics = range(-20, 25, 5)
ax2.set_yticks(ytics)
ax2.set_yticklabels(ytics); # Remove abs() (Also redundant line in your case)

enter image description here

Does this work for you:

ax.set_yticks(np.linspace(-20, 20, 10)) 

Minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1)
ax.set_yticks(np.arange(-20, 25, 5))
plt.show()

Plots: enter image description here

Related