我正在使用matplotlib在python中渲染一些图形,并将它们包含在LaTeX文件中(使用LaTex的漂亮的表格对齐而不是摆弄matplotlib的ImageGrid
等)。 我想使用savefig
创建并保存独立的颜色栏,而无需使用imshow
。
(vlim, vmax
参数以及cmap
可以明确提供)
我能找到的唯一方法是非常复杂的(根据我的理解)在画布上绘制一个硬编码的矩形: http://matplotlib.org/examples/api/colorbar_only.html
是否有一种优雅的方法可以使用matplotlib创建独立的颜色条?
答案 0 :(得分:20)
您可以创建一些虚拟图像然后隐藏它的斧头。在自定义轴中绘制颜色条。
import pylab as pl
import numpy as np
a = np.array([[0,1]])
pl.figure(figsize=(9, 1.5))
img = pl.imshow(a, cmap="Blues")
pl.gca().set_visible(False)
cax = pl.axes([0.1, 0.2, 0.8, 0.6])
pl.colorbar(orientation="h", cax=cax)
pl.savefig("colorbar.pdf")
结果:
答案 1 :(得分:3)
使用与HYRY的答案相同的想法,如果你想要一个"独立的" colorbar在某种意义上说它与图形上的项目无关(与它们的着色方式没有直接关系),您可以执行以下操作:
from matplotlib import pyplot as plt
import numpy as np
# create dummy invisible image
# (use the colormap you want to have on the colorbar)
img = plt.imshow(np.array([[0,1]]), cmap="Oranges")
img.set_visible(False)
plt.colorbar(orientation="vertical")
# add any other things you want to the figure.
plt.plot(np.random.rand(30))
答案 2 :(得分:3)
对http://matplotlib.org/examples/api/colorbar_only.html的引用为我解决了这一问题。该示例有点冗长,因此这是制作独立颜色条(供后代使用)的简单方法...
import matplotlib.pyplot as plt
import matplotlib as mpl
fig = plt.figure()
ax = fig.add_axes([0.05, 0.80, 0.9, 0.1])
cb = mpl.colorbar.ColorbarBase(ax, orientation='horizontal',
cmap='RdBu')
plt.savefig('just_colorbar', bbox_inches='tight')
当然,您可以指定颜色栏的许多其他方面
import matplotlib.pyplot as plt
import matplotlib as mpl
fig = plt.figure()
ax = fig.add_axes([0.05, 0.80, 0.9, 0.1])
cb = mpl.colorbar.ColorbarBase(ax, orientation='horizontal',
cmap='gist_ncar',
norm=mpl.colors.Normalize(0, 10), # vmax and vmin
extend='both',
label='This is a label',
ticks=[0, 3, 6, 9])
plt.savefig('just_colorbar', bbox_inches='tight')
答案 3 :(得分:1)
此解决方案还可独立于ax的内容绘制颜色条。
只需设置fraction = .05
。
代码
import matplotlib as mpl
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
fraction = 1 # .05
norm = mpl.colors.Normalize(vmin=-3, vmax=99)
cbar = ax.figure.colorbar(
mpl.cm.ScalarMappable(norm=norm, cmap='Blues'),
ax=ax, pad=.05, extend='both', fraction=fraction)
ax.axis('off')
plt.show()
答案 4 :(得分:0)
所以,基于this answer here,如果你像我一样想要避免这个丑陋的假plt.imshow(),你可以基本上两行做到这一点:
import matplotlib as mpl
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
col_map = plt.get_cmap('nipy_spectral')
mpl.colorbar.ColorbarBase(ax, cmap=col_map, orientation = 'vertical')
# As for a more fancy example, you can also give an axes by hand:
c_map_ax = fig.add_axes([0.2, 0.8, 0.6, 0.02])
c_map_ax.axes.get_xaxis().set_visible(False)
c_map_ax.axes.get_yaxis().set_visible(False)
# and create another colorbar with:
mpl.colorbar.ColorbarBase(c_map_ax, cmap=col_map, orientation = 'horizontal')