将颜色栏添加到现有轴
我正在做一些交互式绘图,我想添加一个颜色条图例.我不希望颜色条位于其自身的轴中,因此我想将其添加到现有的轴中.我在执行此操作时遇到了困难,因为我发现的大多数示例代码都会为颜色栏创建新的轴.
I'm making some interactive plots and I would like to add a colorbar legend. I don't want the colorbar to be in its own axes, so I want to add it to the existing axes. I'm having difficulties doing this, as most of the example code I have found creates a new axes for the colorbar.
我已经尝试过使用matplotlib.colorbar.ColorbarBase
的以下代码,该代码向现有轴添加了颜色条,但它给了我奇怪的结果,我无法弄清楚如何指定颜色条的属性(例如,在颜色条上的何处放置的轴数和大小)
I have tried the following code using matplotlib.colorbar.ColorbarBase
, which adds a colorbar to an existing axes, but it gives me strange results and I can't figure out how to specify attributes of the colorbar (for instance, where on the axes it is placed and what size it is)
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.cm import coolwarm
import numpy as np
x = np.random.uniform(1, 10, 10)
y = np.random.uniform(1, 10, 10)
v = np.random.uniform(1, 10, 10)
fig, ax = plt.subplots()
s = ax.scatter(x, y, c=v, cmap=coolwarm)
matplotlib.colorbar.ColorbarBase(ax=ax, cmap=coolwarm, values=sorted(v),
orientation="horizontal")
使用fig.colorbar
代替matplotlib.colorbar.ColorbarBase
仍然不能满足我的需求,而且我仍然不知道如何调整颜色条的属性.
Using fig.colorbar
instead ofmatplotlib.colorbar.ColorbarBase
still doesn't give me quite what I want, and I still don't know how to adjust the attributes of the colorbar.
fig.colorbar(s, ax=ax, cax=ax)
比方说,我想在左上角有一个颜色条,延伸到情节顶部的一半左右.我将如何去做?
Let's say I want to have the colorbar in the top left corner, stretching about halfway across the top of the plot. How would I go about doing that?
我最好为此编写一个自定义函数,也许使用LineCollection
?
Am I better off writing a custom function for this, maybe using LineCollection
?
颜色条必须具有自己的轴.但是,您可以创建与上一个轴重叠的轴.然后使用cax
kwarg告诉fig.colorbar
使用新轴.
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax
kwarg to tell fig.colorbar
to use the new axes.
例如:
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()