12
Plot[2x, {x,0,4}];
Plot[x^2, {x,4,8}];

How do I merge these two graphs into one?

Yves Klett
  • 15,383
  • 5
  • 57
  • 124
asd
  • 123
  • 1
  • 1
  • 4

2 Answers2

6

Here's a way that may serve you also for other purposes:

p[x_, left_, right_] := HeavisideTheta[x - left] HeavisideTheta[right - x]
Plot[{2 x p[x, 0, 4], x^2 p[x, 4, 8]}, {x, 0, 8}]

Mathematica graphics

Another example:

tab = Table[x^(1/n) p[x, n, n + 1], {n, 1, 10}]; 
Plot[tab, {x, 0, 8}, PlotStyle -> Thick]

Mathematica graphics

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
5

Update: Using thicker lines to make the difference between various methods visible:

Plot[{ConditionalExpression[2 x, 0 <= x < 4], ConditionalExpression[x^2, 4 < x <= 8]}, {x, 0, 8}, 
 BaseStyle -> Thickness[.02]]

enter image description here

Plot[{Piecewise[{{2 x, 0<=x<4}}, Indeterminate], 
      Piecewise[{{x^2, 4<x<= 8}}, Indeterminate]}, {x, 0, 8}, BaseStyle -> Thickness[.02]]

enter image description here

ct = ConditionalExpression[#, #2] & @@@ Table[{x^(1/n), n < x <= n + 1}, {n, 10}];
Plot[ct, {x, 0, 8}, PlotStyle -> Thickness[.02]]

enter image description here

pw = Piecewise[{{#, #2}}, Indeterminate] & @@@ Table[{x^(1/n), n < x <= n + 1}, {n, 10}];
Plot[pw, {x, 0, 8}, PlotStyle -> Thickness[.02]]

enter image description here

whereas,

p[x_, left_, right_] := HeavisideTheta[x - left] HeavisideTheta[right - x]
Plot[{2 x p[x, 0, 4], x^2 p[x, 4, 8]}, {x, 0, 8}, BaseStyle -> Thickness[.02]]

enter image description here

tab = Table[x^(1/n) p[x, n, n + 1], {n, 1, 10}];
Plot[tab, {x, 0, 8}, PlotStyle -> Thickness[.02]]

enter image description here

Similarly, using Boole in place of HeavisideTheta:

Plot[{2 x Boole[0 <= x <= 4], x^2 Boole[4 < x <= 8]}, {x, 0, 8}, BaseStyle -> Thickness[.02]]

enter image description here

kglr
  • 394,356
  • 18
  • 477
  • 896
  • If single-color plot is acceptable, Piecewise approach can be simplified to Plot[Piecewise[{{2 x, 0 <= x < 4}, {x^2, 4 < x <= 8}}, Indeterminate], {x, 0, 8}] – Bob Hanlon Oct 26 '14 at 18:12
  • @Bob, multiple colors is in fact the reason for the clunkier multiple Piecewises. – kglr Oct 26 '14 at 18:41