如何使用Excel文件中的文本数据列作为x轴?
我在Matlab中导入了一个Excel文件,其中包含两列,一列是数字值,另一列是文本值。 前5行可以看到下面:
ABF-E 0.34
HJK-D -0.54
GHKL-I 1.34
FPLO-5 2.3
KKJLL-T 0.98
我需要绘制Y轴上的数字列和X轴上的文本列。 我可以使用xlsread
和plot
轻松处理数字列,但是我无法pipe理绘制文本列。 我怎么能这样做?
我写了下面的代码,但我不知道该怎么做的x轴:
filename = 'MyData.xlsx'; Sheet = 2 xlRange = 'B1:B60'; Yaxis = xlsread (filename,Sheet,xlRange); Xaxis = ????????; plot(xAxis,Yaxis)
如果有人能帮助我,我将不胜感激。
使用xAxis
文本设置轴的xticklabel
属性 。 你可以这样做:
[~,xAxis] = xlsread(filename,Sheet,'A1:A60'); %// read in text data. Use second output yAxis = xlsread(filename,Sheet,'B1:B60'); %// read in numeric data plot(yAxis) %// This uses 1, 2, 3... as x axis values set(gca,'xtick',1:numel(xAxis)) %// set ticks set(gca,'xticklabel',xAxis) %// set ticklabels with your xAxis xlim([0 numel(xAxis)+1]) %// adjust x axis span
在你的例子中,这产生了:
如果要跳过x轴上的一些标签以使其不那么混乱:定义所需的tickStep
,然后在设置刻度和标签(在两个set
行中)时使用它:
tickStep = 6; [~,xAxis] = xlsread(filename,Sheet,'A1:A60'); %// read in text data. Use second output yAxis = xlsread(filename,Sheet,'B1:B60'); %// read in numeric data plot(yAxis) %// This uses 1, 2, 3... as x axis values set(gca,'xtick',1:tickStep:numel(xAxis)) %// set ticks set(gca,'xticklabel',xAxis(1:tickStep:numel(xAxis))) %// set ticklabels with your xAxis xlim([0 numel(xAxis)+1]) %// adjust x axis span
在这里,我发布了解决这篇文章中所有问题的代码。 我粘贴了graphics的前5个Excel行的代码。 我用来旋转x轴标签的function可以在这里下载: http : //www.mathworks.co.uk/matlabcentral/fileexchange/3486-xticklabelrotate
filename='MyData.xlsx'; %// Name of the file tickStep=1; %// Sets the tick steps Sheet=2; %// Excel sheet number [~,xAxis]=xlsread(filename,Sheet,'A1:A5'); %//Reads text data from Excel file. Uses second output yAxis=xlsread(filename,Sheet,'B1:B5'); %// Reads numeric data from Excel file. plot(1:numel(xAxis),yAxis) %// Plots x and y-Axis in numeric format set(gca,'xtick',1:tickStep:numel(xAxis)) %// Sets the ticks of the x-Axis set(gca,'xticklabel',xAxis(1:tickStep:numel(xAxis))); %// Plots the text data previously read from the Excel file as x-Axis labels xlim([0 numel(xAxis)+1]) %//Adjusts x-Axis span xticklabel_rotate([],90,[],'Fontsize',10) %// Calls and executes the function that rotates the x-Axis labels into a vertical position with a font size of 10