我可以绘制下图,实际上,我有2个数据集(一个颜色映射范围为“酷”,另一个颜色映射为“灰色”):我正在单独绘制每个条形图,使每个条形图的颜色取决于它的高度,即它的“y轴”值:

Current plot

矩形只是每组条形图的平均值 .

Matlab代码是:

% Plot histograms
figure('Color','w');
title('Bar with height-dependant color');
% Convert y1_full vector to colors
y1_color = vals2colormap(y1_full,'cool');
for k = 1:numel(x1_full)
 if (x1_full(k) ~= 0)
  bar_h1 = bar(x1_full(k),y1_full(k),'BarWidth',1);
  set(bar_h1,'FaceColor',y1_color(k,:));
  hold on;
 end
end
% Convert y2_full vector to colors
y2_color = 1-0.8*vals2colormap(y2_full,'gray')
for k = 1:numel(x2_full)
 if (x2_full(k) ~= 0)
  bar_h2 = bar(x2_full(k),y2_full(k),'BarWidth',1);
  set(bar_h2,'FaceColor',y2_color(k,:));
  hold on;
 end
end
% Xlim
xlim([0 max(x2_full)+1]);

现在,我想添加 at the top-right of figure 2 horizontal colorbars ,它代表用于2个数据集('cool'和'gray')中每个数据集的颜色映射,如果可能的话,还添加颜色映射的2个极值 .

这些颜色栏是一种传说,但我不知道如何实现它 .

我尝试过(上面定义了 bar_h1bar_h2 ):

set(bar_h1, 'Location', 'North', 'Position', [0.60 0.70 0.20 0.05]);
set(bar_h2, 'Location', 'North', 'Position', [0.60 0.35 0.20 0.05]);

但我得到这个错误:

Error using matlab.graphics.chart.primitive.Bar/set
There is no Location property on the Bar class.

Error in plot_benchmark_pi_dev (line 89)
set(bar_h1, 'Location', 'North', 'Position', [0.60 0.70 0.20 0.05]);

我也做了:

c1 = colorbar;
c2 = colorbar;
set(c1, 'Location', 'North', 'Position', [0.60 0.70 0.20 0.05]);
set(c2, 'Location', 'North', 'Position', [0.60 0.35 0.20 0.05]);

仍然是一个错误:

Error using matlab.graphics.illustration.ColorBar/set
Invalid or deleted object.

Error in plot_benchmark_pi_dev (line 92)
set(c1, 'Location', 'North', 'Position', [0.60 0.70 0.20 0.05]);

也许我必须直接使用 colormap ,但如何?

如果有人可以帮我绘制这两个水平色图,其范围对应于用于每组条形的范围( coolgray ),这样就可以了 .

ps:用颜色作为高度的函数绘制每个条形图,我使用的是Matlab社区提供的 vals2colormap.m 脚本 .

UPDATE1 :

通过做 :

% Legends
l=legend([bar_h1 bar_h2], 'Data set 1', 'Data set 2');
rect=[0.75, 0.8, 0.1, 0.1];
set(l,'Position',rect,'color','none')

我得到以下结果:

enter image description here

有没有办法将颜色条放入图例而不是只有一种颜色('cool'为洋红色 Data set 1 和'gray'为 Data set 2 )?

问候