How to have have a linear regression on multiple subplots?

7 views (last 30 days)
Hi!
I've done a bit of searching, but to no avail. I've tried using polyfit on each and that doesn't do anything if I do 'polyfit(x, y, 1)' for each subplot. I just throw it in the code for each subplot right after the plot commmand. ie:
plot(Year, Solar, 'ks')
polyfit(Year, Solar, 1)
This probably isn't correct but our professor didn't explain this very clearly.
The only thing I have figured out how to do is after I run the program and everything plots like in the screenshot below, I can use the basic fitting tool to plot a linear regression. However, it only allows me to do it on one plot at a time. Sort of frustrated. Thank you for any help you may provide.
~ Collin
Plots
Code
% Defining the Google Search Criterion Year=[2004:1:2015]; Solar=[19 19 24 26 31 36 37 41 37 31 31 30]; Nuclear=[26 23 22 18 18 17 16 39 14 14 14 13]; Wind=[75 71 70 79 83 100 77 72 47 46 33 35];
% Defining the First Plot subplot(3,1,1); plot(Year, Solar, 'ks'); xlabel('Year'); ylabel('Solar Panel Searches'); title('Google Search Results for Solar Panels') hold on;
% Defining the Second Plot subplot(3,1,2); plot(Year, Nuclear, 'r*'); xlabel('Year'); ylabel('Nuclear Energy Searches'); title('Google Search Results for Nuclear Energy') hold on;
% Defining the Third and Final Plot subplot(3,1,3); plot(Year, Wind, 'bx'); xlabel('Year'); ylabel('Wind Turbine Searches'); title('Google Search Results for Wind Turbines') hold on;

Answers (1)

Star Strider
Star Strider on 14 Feb 2016
It is difficult to follow what you’re doing. To use polyfit to actually create a regression line to plot, you also have to use the polyval function.
For example:
Solar_Parms = polyfit(Year, Solar, 1);
Solar_Fit = polyval(Solar_Parms, Year);
plot(Year, Solar, 'ks')
hold on
plot(Year, Solar_Fit, '-k')
hold off
  2 Comments
Collin Kinder
Collin Kinder on 14 Feb 2016
Perfect answer, thank you! So it worked flawlessly.
However, do you know how I can get the equations to post on each subplot like I have above? Like the y= equation on the first subplot above?
Here's what we have so far:
Star Strider
Star Strider on 14 Feb 2016
My pleasure!
Use a text call to print the equations to the plot. For example, the top one could be:
pm = ['-+'];
text(2005, min(ylim)+0.75*(diff(ylim)), sprintf('y = %0.2f %s %.2e', Solar_Parms(1), pm(2+sign(Solar_Parms(2))), abs(Solar_Parms(2))))
Be sure to include the ‘pm’ line! I tested the sprintf call but not the entire code. It should work.

Sign in to comment.

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!