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:
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!
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)