Python Matplotlib 颜色条背景和标签放置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18403226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib colorbar background and label placement
提问by oli
Up until recently I have been using Mathematica for my plots. Although it was a real pain and everything had to be done manually, the results where very close to what I wanted. One example is the following:
直到最近,我一直在使用 Mathematica 进行绘图。虽然这真的很痛苦,而且一切都必须手动完成,但结果非常接近我想要的。一个例子如下:
I really like the grey rounded rectangle in the background of the colorbar. While everything had to be adjusted manually in Mathematica, matplotlib is a lot more automatic and already produced nice results.
我真的很喜欢颜色条背景中的灰色圆角矩形。虽然一切都必须在 Mathematica 中手动调整,但 matplotlib 更加自动化并且已经产生了不错的结果。
But there are still two problems I have:
但是我还有两个问题:
- I don't know how to do a rounded rectangle in the background. I looked at the fancybbox patch but didn't get it to work with the colorbar as I want it to. What is the best way to get something like the Mathematica box? For the legend in plots there seems to be a fancy bbox option... but not for colorbars
- When I use the "lesser sign" (<) the label of colorbar moves too far to the right. How can I adjust this (maybe even "in-between" the numbers as in the Mathematica plot)?
- 我不知道如何在背景中做一个圆角矩形。我查看了fancybbox 补丁,但没有像我想要的那样使用颜色条。获得像 Mathematica 盒子这样的东西的最佳方法是什么?对于图中的图例,似乎有一个花哨的 bbox 选项......但不适用于颜色条
- 当我使用“小号”(<)时,颜色条的标签向右移动太远。我该如何调整(甚至可能是 Mathematica 图中的“中间”数字)?
I am looking forward to any suggestions pointing in the right direction :).
我期待着任何指向正确方向的建议:)。
采纳答案by mwil.me
To your second question: you can use a negative labelpad
value to move the label back towards the ticklabels, like this:
对于您的第二个问题:您可以使用负值labelpad
将标签移回刻度标签,如下所示:
import numpy as np
import matplotlib.pyplot as plt
data = np.linspace(0, 10, num=256).reshape(16,16)
cf = plt.contourf(data, levels=(0, 2.5, 5, 7.5, 10))
cb = plt.colorbar(cf)
cb.set_ticklabels([r'$<10^{0}$', 1, 2, r'^{14}$', r'^{14}+12345678$'])
cb.set_label(r'$n_e$ in $m^{-3}$', labelpad=-40, y=0.45)
plt.show()
Using the parameter y
, you can additionally move the label up or down for better symmetry.
使用参数y
,您还可以上下移动标签以获得更好的对称性。
The argument of labelpad
is given in points (1/72 inch). y
accepts values in [0, 1]
, 0.0
is the lower border and 1.0
the upper.
的参数labelpad
以点(1/72 英寸)为单位给出。y
接受 中的值[0, 1]
,0.0
是下边框和1.0
上边框。
The result:
结果: