matlab 画 柱状图 以及 柱状图内 拟合直线

画柱状图很简单, 柱状图上画一条直线找到方法也没啥特别的,但要把柱状图把 最高点拟合出直线,如果直接用拟合得到的方程, 会发现 效果不好,原因就在于 柱状图的 横坐标和 实际拟合数据 的 比例不一致。所以,需要 基于 柱状图的 横坐标 求 拟合方程, 这样 画出来的效果 就吻合了

[NUM,TXT,RAW]=xlsread('mergedabsgroup-April032019.xlsx');

age = NUM(:, 1);

country = TXT(2:end,10);

agedif = NUM(:, 7);
absagedif = NUM(:, 9);


[m, n] = size(age);
m;
n;

% 最大 最小 年龄
CHN_MAXAGE = max(age);
CHN_MINAGE = min(age);

% 年龄区间长度
LEN = 9; 
% 区间个数
INTERVALS = floor((CHN_MAXAGE -  CHN_MINAGE - 1) / LEN +1);

XTickLabels =cell(INTERVALS, 1);
for n = 1:INTERVALS
    XTickLabels{n, 1} = [num2str(CHN_MINAGE+(n-1)* LEN)   '-'   num2str(CHN_MINAGE + n* LEN - 1) ];
end

Agedifs = cell(INTERVALS, 1);
AbsAgedifs = cell(INTERVALS, 1);
agesDebug = cell(INTERVALS, 1);

%Agedifs = zeros(INTERVALS, 100);

%组别名称
team = 'CHN';

chn = 0;
for n = 1:m
    if(strcmp(country(n), team) == 1)
        chn = chn + 1;
        
        index = floor((age(n) - CHN_MINAGE) / LEN ) + 1;
        
        % debug info
        agesDebug{index, 1} = [agesDebug{index, 1} age(n)];
        
        Agedifs{index, 1} = [Agedifs{index, 1} agedif(n)]
        
        AbsAgedifs{index, 1} = [AbsAgedifs{index, 1} absagedif(n)]
    end
end

means = [];
absMeans = [];

if(strcmp('EUR', team) == 1)
    INTERVALS = 6;
end

vars = [];
absVars = [];
for n = 1:INTERVALS
    means = [means mean(Agedifs{n, 1})];
    absMeans = [absMeans mean(AbsAgedifs{n, 1})];
    
    vars = [vars std(Agedifs{n, 1})];
    absVars = [absVars std(AbsAgedifs{n, 1})];    
end

% 画出每个年龄段的均值
%plot(means);
%figure();
% 画出每个年龄段的绝对值的均值
%plot(absMeans);

means = means';
vars = vars';

res1 = [means vars];
b = bar(res1);
grid on;
set(gca,'XTickLabel', XTickLabels); %
legend('mean','var');

xlabel('x axis ');
ylabel('y axis');

% 拟合
agesIndex = CHN_MINAGE+ floor(LEN/2): LEN : CHN_MINAGE+LEN * INTERVALS-1;
agesIndex = agesIndex';
p = polyfit(agesIndex, means, 1);

psuAges = [1:1:INTERVALS]';
p2 = polyfit(psuAges, means, 1);

startV = polyval(p2, 0);
endV = polyval(p2, 8);
xrange = get(gca,'xlim');
hold on;

plot(xrange,[startV endV],'r-');

figure();
x1=linspace(0, 80);  
y1=polyval(p,x1);  
plot(agesIndex, means, '*', x1, y1); 
%%%%%%%%%%%%%%%%%%%%%
% 以下 处理绝对值
% figure();
% 
% 
% means = absMeans';
% vars = absVars';
% 
% res1 = [means vars];
% b = bar(res1);
% grid on;
% set(gca,'XTickLabel', XTickLabels); %
% legend('mean','var');
% 
% xlabel('x axis ');
% ylabel('y axis');




你可能感兴趣的:(Tools)