matlab - 如何在分组条形图的顶部绘制一条线?

标签 matlab plot bar-chart

我有一个分组条形图,我想比较这些值。即,我的意思是我想使用线条将其可视化。我尝试了以下代码,输出也如下

Y=rand(5,5)
str = {'A'; 'B'; 'C'; 'D'; 'E';};
bar_widh=0.2;
h = bar(Y,bar_widh);
hold on;plot(Y,'b');
set(gca, 'XTickLabel',str, 'XTick',1:numel(str))
grid on
l = cell(1,5);
l{1}='P'; l{2}='Q'; l{3}='R'; l{4}='S'; l{5}='T'; 
legend(h,l);

我得到以下输出:

enter image description here

我想可视化条形的最小数量/较大数量。在某些情况下,较大的值不好。你能帮我绘制与条形相同的线条颜色

我得到的输出如下

enter image description here

最佳答案

你可以试试这个:

Y=rand(5,5);
str = {'A'; 'B'; 'C'; 'D'; 'E';};
bar_widh=0.2;

figure; hold on;grid on
h = bar(Y,bar_widh);

% to highlight the minimum of each group, 
% copy data into a new matrix
Y_ = Y; 
% find the minimum values and make the rest zeors
Y_(Y_~=repmat(min(Y_,[],1),size(Y,1),1)) = 0;
% then plot with so sort of highlighting
h2 = bar(Y_,0.5);

pause(0.1) % pause to allow bars to be drawn

% now go through each group of bars and plot the line
for i = 1:numel(h)
    x = h(i).XData + h(i).XOffset; % find the x coordinates where the bars are plotted
    ax = plot(x,Y(:,i)); % plot the line
    % set color of the bars the same as the line
    h(i).FaceColor = ax.Color; 
    h2(i).FaceColor = ax.Color;
end

set(gca, 'XTickLabel',str, 'XTick',1:numel(str))
legend('P','Q','R','S','T');

h(i).XData

是第i组条形的中心坐标。

例如,就您而言:

h(1).XData = [ 1 2 3 4 5 ]; % group P
h(2).XData = [ 1 2 3 4 5 ]; % group Q
...
h(5).XData = [ 1 2 3 4 5 ]; % group T

h(i).XOffset

是组中每个条形相对于其相应中心坐标的偏移值。

例如,就您而言:

h(1).XOffset = -0.3077; % group P
h(2).XOffset = -0.1538; % group Q
...
h(5).XOffset = 0.3077; % group T

不突出显示最小值 enter image description here

突出显示最小值 enter image description here

关于matlab - 如何在分组条形图的顶部绘制一条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43719292/

相关文章:

matlab - 从列的非零条目中删除列均值

Matlab:查找点(x,y)包围的面积

r - 从 Rstudio 保存为 pdf

python - 无法并排绘制多个水平条

c++ - 使用带有 MEX Wrapper 的辅助 C 文件从 MATLAB 2016 调用 C++ 代码时遇到问题

matlab - 在不同大小的不同单元格数组中查找重复值的最快方法

python - Pandas 将数据框绘制为多个条形图

r - R散点图中的轴位置

r - 是否有 R 函数可以调整条形图轴的比例?

python - 如何控制 seaborn 条形图中条形之间的空白?