Reputation: 1028
How is it possible to get a positive +-sign in front of the y tick labels in a matplotlib subplot?
Upvotes: 1
Views: 714
Reputation: 25093
Quick and dirty (I'd say that methods' names are self-explanatory, aren't they?)
ax = plt.gca()
ylabels = ax.get_ylabels()
for ylabel in ylabels: ylabel.set_text('+'+ylabel.get_text())
ax.set_ylabels(ylabels)
A little more kosher
import matplotlib.ticker as ticker
...
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter("%+g"))
plt.plot(...)
...
The second part has been written using https://matplotlib.org/gallery/ticks_and_spines/tick-formatters.html as a reference.
Addendum
In a comment the OP asked "… what can I do to avoid a +-sign in front of the 0?".
A possible solution can be
...
bare0 = lambda y, pos: ('%+g' if y>0 else '%g')%y
ax.yaxis.set_major_formatter(ticker.FuncFormatter(bare0))
...
See https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FuncFormatter for the details.
Upvotes: 4
Reputation: 394
Maybe like this ?
plt.yticks(np.arange(6), ('0', '+1', '+2', '+3', '+4', '+5'))
Upvotes: -1