Home 世界杯开幕战 matlab histogram绘制直方图并标注对应数值

matlab histogram绘制直方图并标注对应数值

备注:程序适用于matlab读取excel文件,对文件中的数据绘制直方图,并在直方图上标注对应数值。

1. 读取excel文件。

没有excel文件,则将数据存储于一维数组中。

% 读取excel文件

excel_path = 'E:\test_result_1.xlsx';

% 保存数据

excel_data = importdata(excel_path); % 获得一个结构体

text_data = excel_data.textdata; % 获取数据

data = text_data(:,2); % 取第二列数据

data_length = length(data);

data1 = zeros(data_length,1);

for i = 1:data_length

data1(i) = str2num(cell2mat(data(i))); % 保存数据在data1中

end

2. 使用histogram绘制直方图。

% 画直方图

h = histogram(data1);

3. 标注数值。

0.03和3都是根据直方图的具体情况调整标注信息的位置设置的。

x1 = h.BinEdges; % 横坐标值

y1 = h.Values; % 纵坐标值

x = (x1(2:end) + x1(1:end-1))/2 - 0.003; % 标注位置的横坐标,0.03可以根据具体情况进行调整。

y = y1 + 3; % 标注位置的纵坐标,3可以根据具体情况进行调整。

for i = 1:length(y)

text(x(i),y(i),num2str(y1(i)));

% text要求标注信息为字符串,因此num2str(y1(i))

end

4. 结果图。

5. 完整代码。

% 读取excel文件

excel_path = 'E:\test_result_1.xlsx';

% 'E:\bsq\Sleep_Apnea\SpO2\result\test_result_9.xlsx'

excel_data = importdata(excel_path);

text_data = excel_data.textdata;

data = text_data(:,2); % 取第二列数据

data_length = length(data);

data1 = zeros(data_length,1);

for i = 1:data_length

data1(i) = str2num(cell2mat(data(i)));

end

% 画直方图

h = histogram(data1);

x1 = h.BinEdges;

y1 = h.Values;

x = (x1(2:end) + x1(1:end-1))/2 - 0.003;

y = y1 + 3;

for i = 1:length(y)

text(x(i),y(i),num2str(y1(i)));

end