How to use hold command with Plotyy and Subplot?

Dear Matlab Users,
I am facing a problem on applying hold command along with both Plotyy and subplot. Here, I am providng my code and attached my sample data for your convenience. Here, the subplot consists of 4 plotyy figures with 2*2 grid, and each plotyy fig. contains 4 plots with 2 at the left Y-axis, 1 at the right Y-axis and one hline plot for the threshold value. For adding 2 plots at the left Y-axis, I am using hold (ax1(1)), hold(ax2(1)), hold(ax3(1)), and hold(ax4(1)) in the subplot 1, 2, 3, and 4 respectively. When, I am running the attached code, it is showing an error on handle axis.
Please help me to know where I am going wrong in the attached code.
Please find the attached sample data and code matfile.
Thank you for your time.

 채택된 답변

dpb
dpb 2020년 1월 16일
Ver 2
[y,t]=xlsread('Sample Data.xlsx');
t=datetime(t(2:end,1),'inputformat','MM/dd/uuuu','format','MMM yy');
mos=(year(t(end))-year(t(1)))*12+1+6*(month(t(end))>6);
ttk=datetime(year(t(1)),1:6:mos,1,'format','MMM yy');
for i=1:4
hAx(i)=subplot(2,2,i);
hL{i,1}=plot(t,y(:,1:2),'linewidth',1.5);
hL{i,1}=[hL{i,1}; ...
yline(0.15,'m','GHE = 0.5', ...
'linewidth',2.5, ...
'labelHorizontalAlign','center')];
xticks(ttk)
hAx(i).XTickLabelRotation=90;
hAx(i).XAxis.FontSize=9;
yyaxis right
set(gca,'YColor','r')
hL{i,2}=plot(t,y(:,i+2),'r');
end
return
results in
untitled.jpg
Really too many ticks for the space with subplot() unless you're going to make the display full screen, but it's what asked for...

댓글 수: 5

RP
RP 2020년 1월 17일
편집: RP 2020년 1월 17일
Dear DPB,
Thank you very much for your help. Actually, here I am trying to find out the comovement between the financial variables. Your suggested code is the exact way what I really expected in my analysis. But, still I have some queries for the final arrangement of the subplots as follows.
  1. Here, I just provided a small part of my data to learn coding. Actually, I have 12 countries data with each country having 5 subplots. So, I am thinking to split 6 country's data with 6*5 = 30 subplots per page. In this context, my matlab grid per page will be 6rows*5cols. Therefore, The left y-axis variables (i.e. :,1:2) will vary for each country in each row. I mean, for the 1st row and 5 columns, I will have same left y-axis variables on the basis of one country, but in the next row, the particular variables will change on the basis of different country's data. So, here, how can I call loop for the left y-axis variables for arranging the hAx(i)=subplot(6,5,i), and how the right y-axis will be called rather than i+2? In short, I am thinking to arrange each country's subplot(i.e. 5 subplots) in a single row. Here, please suggest me how to call loop for the left and right y-axis variables?
  2. How can I call legend and title for each subplot in a loop so that it will be easier to identify the particular comovements?
  3. The yline you arranged is bymistakenly wrong. I wanted to draw the hline in the left y-axis when left-yaxis= 0.5 which is my threshold level. But, you write hline when y=0.15. So, if I change as follows,
yline(0.5,'m','GHE = 0.5', ...
'linewidth',2.5, ...
'labelHorizontalAlign','center')];
will it be right?
4. I think adding of too many X-ticks on the X-axis is making the entire subplots messy. So, if I change in your suggested code from 6 to 8 to arrange the individual month names in 8 months gap as follows,
mos=(year(t(end))-year(t(1)))*12+1+8*(month(t(end))>8);
ttk=datetime(year(t(1)),1:8:mos,1,'format','MMM yy');
will it be okay in terms of apperance of all subplots? The x-ticks will be same for all subplots. So, I am thinking to provide the x-ticks only for the last row of the entire grid which can represent for individual subplots in each column. Will it be good idea to arrange all plots in a neat manner? If so, Please suggest me how can I call x-ticks only for the last row of the subplot?
Actually, I am new in matlab, and doing by learing. Your suggestions on my previous queries will definitely help me to learn further coding in Matlab.
Please help and suggest to a needful.
Thank you for your time.
dpb
dpb 2020년 1월 17일
편집: dpb 2020년 1월 17일
Try some of this on your own and see where you get stuck; you'll learn faster than by someone else continuing to spoon feed. :)
Some comments in general..
  1. four subplots per figure are already starting to get crowded; 30 on a page will be miniscule. Have you actually just created that array of axes to see what it looks like? My guess is you'll just have blobs that aren't distinguishable as to what you're going to be looking at...but, you can always try it and see if it will let you see what you're trying to visualize or not.
  2. As far as the subscripting, you just have to work out the algebra of which columns of data represent which country and belong on which plot by row and column. It's some linear combination of row and column depending upon how the data are stored but I don't know which is which; only you have that information at this point. Look at the way I did it above for the basic idea; you're just adding another variable into the mix with which to keep track of which data sets go where.
  3. legend and title can be added inside the loop just as if you were writing the code linearly as you did previously. As noted before, you've got to then have either a set of text by array indices that you reference for the content to write for a given axes or be able to compute which is which just from the sequence numbers or row, column. If you have different countries, probably the simplest is to create a list of those names in the order you want. Or, you may have some place where that data is associated with the financial data you're downloading so you can use it. Again, those are details you've not provided.
  4. On the value for the horizontal line, I just copied your code...if you made a typo, so did I. :) I would note, however, that 0.5 is going to be way out of range on the LH axes y values you've got which will then make the actual data itself tiny little lines at the bottom on that axis. There's also a major discrepancy in magnitude for the RH axis from plot to plot that if continue to let it auto-range, it will always fill the screen and the LH axis will be very low in comparison.
  5. On xticks, I'd suggest for starters just let MATLAB auto-fit them. Even only one/year for 24 years is pushing it on the 4x4 layout; you're making even smaller with proposed 6x5. Look at the logic I wrote to figure out how many months are in six-months intervals over the time of the data to figure out how many would be for any given spacing. If you really are going to do that, should rewrite that computation in terms of a variable for the spacing instead of hardcoding in a given interval like 6 or 8. Probably the most user-friendly way would be to pick one of the even divisors of 12 and compute that number as 1-, 2-, 3-,... ticks/year. For as much data as you have and for such small plot areas as you'll get for each subplot, I think I'd at least initially just let it auto-label as discussed above.
RP
RP 2020년 1월 18일
Thank you very much for your valuable general suggestions based on which I will definitely learn and apply in my full-sample analysis. But, I didn't understand one of your suggestion in terms of the arrangment of xticks "Probably the most user-friendly way would be to pick one of the even divisors of 12 and compute that number as 1-, 2-, 3-,... ticks/year. ", here 1-,2-,3- stands for?
Thank you very much for your help.
dpb
dpb 2020년 1월 18일
편집: dpb 2020년 1월 18일
Simply shorthand to not write 1-tick/year, 2-ticks/year, 3-ticks/year, ...
RP
RP 2020년 1월 18일
Okay, I understood. Thank you very much for your help and suggestions.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

dpb
dpb 2020년 1월 15일
편집: dpb 2020년 1월 15일
Using the features TMW has given us more recently...in particular, datetime and yyaxis along with using some data organization by indexing will help immensely to simplify...the following code generated
untitled.jpg
I didn't bother to finish the rest of the annotation, etc., that should be simple enough to insert into the loop with some preliminaries to save the needed info for labels, etc.
The line handles and basic axis handles are all saved so can also make modifications outside the loop if necessary/desired.
[y,t]=xlsread('Sample Data.xlsx');
t=datetime(t(2:end,1),'inputformat','MM/dd/uuuu');
for i=1:4
hAx(i)=subplot(2,2,i);
hL{i,1}=plot(t,y(:,1:2));
yyaxis right
set(gca,'YColor','r')
hL{i,2}=plot(t,y(:,i+2),'r');
end

댓글 수: 3

RP
RP 2020년 1월 16일
Thank you very much for your response. This is partially right what I really expected. But, my each plotyy figure in the subplot should consists of 4 lines, but here, each fig. contains 3 lines, that means the hline which I have defined in my previous code to identify the threshold value of 0.5 isn't there. Please suggest to me how can I add hline code in your suggested code?
Further, I have two following queries on your suggested code
  1. In "hL{i,1}=plot(t,y(:,1:2));", what 1:2 indicates? I think you have called 1st and 2nd column in the left Y-axis, right?
  2. in "hL{i,2}=plot(t,y(:,i+2),'r')" what "i+2" indicates although I understand this is for right Y-axis?
Please suggest to me for which I shall be able to proceed with your suggestion.
Thank you for your time.
dpb
dpb 2020년 1월 16일
편집: dpb 2020년 1월 16일
I just outlined the general form; finish up the refinements as desired.
Add your hline call to whichever axis you desire it to reside on--if left, before the yyaxis call, if right, after.
There is no base hline function that matches your calling syntax so can't replicate what that function does, precisely, anyways...
>> which -all hline
C:\ML_R2017\toolbox\stats\stats\private\hline.m % Private to stats
>>
Only a private function; let's see what it expects for inputs, anyways...
>> help private/hline
hline draws horizontal lines
hline(X) draws one horizontal line for each element in vector x
hline(AX,X) draws the lines to the axes specified in AX
hline(X,...) accepts HG param/value pairs for line objects
...
So, the usage you have doesn't match up with the expected inputs of just a numeric value or array of such so not same function...
For the Q?,
  1. Yes. You used two calls, no reason to not just address the columns desired by subscripting,
  2. Yes, again. The RH axis column is 3 thru 6; or index plus two of the index number for the four subplots. That's just a result of the particular order in the y array of the data and what you chose to put on each axis/plot. Could have been any other; just turned out in this case to be quite a simple way to get the ones wanted; sometimes it's not so easy so may have to resort to look up tables or somesuch.
Read up on matrix/array addressing in the Getting Started section on efficient use of MATLAB arrays and vector subscripting.
dpb
dpb 2020년 1월 16일
"There is no base hline function that matches your calling syntax so can't replicate what that function does, precisely, anyways..."
Oh. I see R2018 release introduced yline which would work. I was using R2017b and didn't have later release installed at the time. Nevertheless, hline appears in error or a local function...

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Axis Labels에 대해 자세히 알아보기

질문:

RP
2020년 1월 15일

댓글:

RP
2020년 1월 18일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by