(Answer) (Category) LON-CAPA User Help : (Category) Authoring : (Category) Authoring Problems :
How can I create a dynamic plot of a piecewise defined function?
I want to plot a piecewise defined function similar to
 f(x)= a*x + b     if (x < 4.5)
 f(x)= a*x         if (x >= 4.5)


Below is xml for creating a dynamic plot based on this. The work is done in the <script ></script > block that generates the data sets used in the plot.

 <script type="loncapa/perl" >
 $a = &random(2,5,1);
 $b = &random(3,6,1);
 
 for ($x = 0; $x<4.5; $x+= 0.05) {
     push @X, $x;
     push @Y, $a*$x + $b;
 }
 
 for ($x = 4.5; $x<=10; $x+= 0.05) {
     push @X, $x;
     push @Y, $a*$x;
 }
 </script >
 <gnuplot font="medium" width="500" grid="on" height="400" border="on" 
          fgcolor="x000000" alttag="dynamically generated plot" align="center" 
          bgcolor="xffffff" transparent="off" >
     <curve linestyle="lines" pointsize="1" pointtype="1" color="x000000" 
      name="">
         <data >@X</data >
         <data >@Y</data >
     </curve >
 </gnuplot >
The above script works, but it produces a plot that looks like the one below:
(dynamic_plot_piecewise_crappy_example.gif)


A better solution is to use two seperate <curve > statements to plot two separate curves. So on the second piece of the function we use @X2 and @Y2 instead of @X and @Y. Then in the <gnuplot > tag we include a second <curve > sub-tag.

 <script type="loncapa/perl" >
 $a = &random(2,5,1);
 $b = &random(3,6,1);
 
 for ($x = 0; $x<4.5; $x+= 0.05) {
     push @X, $x;
     push @Y, $a*$x + $b;
 }
 
 for ($x = 4.5; $x<=10; $x+= 0.05) {
     push @X2, $x;
     push @Y2, $a*$x;
 }
 </script >
 <gnuplot font="medium" width="500" grid="on" height="400" border="on" 
          fgcolor="x000000" alttag="dynamically generated plot" align="center" 
          bgcolor="xffffff" transparent="off" >
     <curve linestyle="lines" pointsize="1" pointtype="1" color="x000000" 
      name="" >
         <data >@X</data >
         <data >@Y</data >
     </curve >
     <curve linestyle="lines" pointsize="1" pointtype="1" color="x000000" 
      name="" >
         <data >@X2</data >
         <data >@Y2</data >
     </curve >
 </gnuplot >

(dynamic_plot_piecewise_better.gif)

This is still not a desirable result. Typically one wants an open circle or closed circle defining the domain of each piece. Unfortunately there is no easy way to do this in gnuplot currently. If this effect is desired, perhaps using a static image and a randomlabel problem would be the best approach. A second solution would be to add data which draws a circle to your curves.

[Append to This Answer]
Previous: (Answer) How do I make a dynamically generated plot?
Next: (Answer) Gnuplot Example 1
This document is: http://help.loncapa.org/cgi-bin/fom?file=155
[Search] [Appearance] [Show This Answer As Text]
This is a Faq-O-Matic 2.719.
This FAQ administered by the LON-CAPA team at MSU. Submit a help request ticket to contact us.