How can I set a color gradient on my bar plot?
27 ビュー (過去 30 日間)
古いコメントを表示
Hello!
I have the following vector of values:
[1 2 3 4 5 6 7 8 9 10; -1.8 -1.7 -1.3 -1.4 -1.8 -1.7 -1.6 -1.7 -1.5 -1.4].
The first line corresponds to the x-axis whereas the second is the y-axis. I would like to plot these values in a 2D bar plot with a color gradient. I would like to color the bars according to their height in order to highlight the maximum value (-1.3). How can I do that?
Many thanks in advance!
0 件のコメント
採用された回答
Robert
2016 年 8 月 8 日
編集済み: Robert
2016 年 8 月 9 日
The most direct way in my opinion is to call bar once for each bar in your plot, assigning individual colors that way.
y = [-1.8 -1.7 -1.3 -1.4 -1.8 -1.7 -1.6 -1.7 -1.5 -1.4];
N = length(y);
clr = interp1(linspace(min(y),max(y),100),parula(100),y);
bar(nan(size(y))); % ghost bar plot to get our axis labels
hold on
for ii = 1:N
bar(ii,y(ii),'FaceColor',clr(ii,:));
hold on
end
hold off
But you may want a way to color existing bar charts and/or that allows you to interact with the barseries object as you would with a single call to bar.
A commenter at undocumentedmatlab.com posted a means of editing a bar plot to have separate colors (in R2014b or newer) by editing the Face property of the bar plot as follows.
y = [-1.8 -1.7 -1.3 -1.4 -1.8 -1.7 -1.6 -1.7 -1.5 -1.4];
N = length(y);
hBar = bar(y); % can use x = 1:N but don't have to
StripData is one way Face organizes its data; VertexIndices is another. We need to switch from StripData to VertexIndices in order to color the bars.
hBar.Face.StripData = []; % Delete the existing StripData
Each bar is described by its four corners. We need to put them in an order that doesn't cross the middle of the rectangle. Here we use 1, 2, 4, 3. You can try vi = 1:4*N here to see why we need to do this.
vi = [1:4:N*4; 2:4:N*4; 4:4:N*4; 3:4:N*4];
vi = uint32(vi(:)');
And then we can map the values to colors with interp1 and colormap (or you can use any other color scheme you want).
clr = interp1(linspace(min(y),max(y),100),parula(100),y);
clr = uint8(clr'*255); % convert to the type and shape we need
clr(4,:) = 255; % we need to add a row for opacity. 255 is fully opaque.
And finally apply our changes.
hBar.Face.VertexIndices = vi;
hBar.Face.ColorBinding = 'discrete';
hBar.Face.ColorData = clr;
Whew! You should see individual colors on each bar now! Each time the plot is updated, you will have to re-apply the changes by executing (again)
hBar.Face.StripData = [];
hBar.Face.VertexIndices = vi;
0 件のコメント
その他の回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Data Distribution Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!