python - matplotlib 中的正号刻度标签

标签 python matplotlib plot

如何在 matplotlib 子图中的 y 刻度标签前面获得正 + 号? enter image description here

最佳答案

快速而肮脏(我想说方法的名称是不言自明的,不是吗?)

ax = plt.gca()
ylabels = ax.get_ylabels()
for ylabel in ylabels: ylabel.set_text('+'+ylabel.get_text()) 
ax.set_ylabels(ylabels)

更加犹太洁食

import matplotlib.ticker as ticker
...
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter("%+g"))
plt.plot(...)
...

第二部分是使用 https://matplotlib.org/gallery/ticks_and_spines/tick-formatters.html 编写的作为引用。

<小时/>

附录

OP 在评论中询问“……我该怎么做才能避免 0 前面出现 + 号?”

可能的解决方案是

...
bare0 = lambda y, pos: ('%+g' if y>0 else '%g')%y
ax.yaxis.set_major_formatter(ticker.FuncFormatter(bare0))
...

参见https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FuncFormatter了解详情。

关于python - matplotlib 中的正号刻度标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57003343/

相关文章:

python - 将重叠图像相互移动以获得准确的差异

python - 在 Kivy 中显示 numpy/opencv/matplotlib 图像

Python 导入为元组

python - boxPoints 返回负 y 值

python - 突出显示 matplotlib 矩阵上的某些点

python - Matplotlib + Pylab 导入错误

python - 如何在 matplotlib 中绘制 5 组条形图?

python - 值错误: invalid literal for int() with base 10 in tensorflow

r - 如何防止在 R 中调整字体、绘图对象等的大小?

python - 为什么 plt.figure(figsize=(X,y)) 不改变我的 .hist 和 .plot 的大小?