创建一个多个水平线图,绘制多年的众多变量

时间:2014-03-01 08:35:16

标签: matlab plot line

我有9年的数据,每个数据都保存了相同的变量,例如夏天,最温暖的月份,阳光照射的月份等等。我想将每年的变量绘制成一组水平线,组合在一起,具有不同的线条属性。所以年份将在y轴上,而月份将在x轴上。

对不起,这有点模糊,我不确定如何描述它。

1 个答案:

答案 0 :(得分:1)

以下代码可能会让您接近(如果不是确切的话)您正在寻找的内容 -

%% PLOT YEARLY DATA ON TOP OF EACH OTHER
%% NOTE: Tinker with the text and plot properties to put Y labels and the custom-made legend at custom positions on the plot

%% Data - Insert your data in this way
years = 2001:2009;
months_string = {'Jan'; 'Feb'; 'Mar';'Apr'; 'May'; 'Jun';'Jul'; 'Aug'; 'Sep';'Oct'; 'Nov'; 'Dec'};
num_years = numel(years);
num_months = numel(months_string);

for count = 1:num_years
    data.year(count).summer = 12.*rand(num_months,1);
    data.year(count).warmest_months = 48*rand(num_months,1);
    data.year(count).len_sunlit = 23*rand(num_months,1);
end

%% Params
offset_factor = 0.5;
x_legend_offset_factor = 0.75;
extension_top_legend = 0.2;
ylabel_pos = -1.0;

%% Add some useful info the struct, to be used later on
for count = 1:num_years
    data.year(count).minval = min([ min(data.year(count).summer) min(data.year(count).warmest_months) min(data.year(count).len_sunlit)]);
    data.year(count).maxval = max([ max(data.year(count).summer) max(data.year(count).warmest_months) max(data.year(count).len_sunlit)]);
    data.year(count).range1 = data.year(count).maxval - data.year(count).minval;
end

%% Global Offset
max_range = max(extractfield(data.year,'range1'));
global_offset = offset_factor*max_range;

off1 = zeros(num_years,1);
for count = 2:num_years
    off1(count) = data.year(count-1).maxval + global_offset;
end
off1 = cumsum(off1);

%% Plot
figure,hold on,grid on,set(gca, 'YTick', []);
xlabel('Months');

for count = 1:num_years
    plot(1:num_months,off1(count)+data.year(count).summer,'b')
    plot(1:num_months,off1(count)+data.year(count).warmest_months,'r')
    plot(1:num_months,off1(count)+data.year(count).len_sunlit,'g')
    text(ylabel_pos,(data.year(count).minval+data.year(count).maxval)/2+off1(count),['Year -  ',num2str(years(count))])
end

% Find Y Limits and extending the plot at the top to accomodate the custom legend
ylimit = off1(num_years) + data.year(num_years).maxval;
ylim_1 = data.year(1).minval;
ylim_2 = ylimit+(ylimit - data.year(1).minval)*extension_top_legend;
ylim([ylim_1 ylim_2])

xlimits = xlim;
x_legend_offset = (xlimits(2) - xlimits(1))*x_legend_offset_factor;

% Adding text to resemble legends
txstr(1) = {'\color{blue} Summer'};
txstr(2) = {'\color{red} Warmest Months'};
txstr(3) = {'\color{green} Length of sunlit months'};
text(x_legend_offset,ylim_2,txstr,'HorizontalAlignment','center','EdgeColor','red','LineWidth',3)
set(gca, 'XTickLabel',months_string, 'XTick',1:numel(months_string))

对于随机数据,该图可能看起来像 -

enter image description here

如果上述代码适合您,请告诉我们!