5
$\begingroup$

This is a function that takes a function, turn it into a vector, then plots the vector and its contour.

plot[ϕ_] := 
     Module[{Efield = -{D[ϕ, x], D[ϕ, y]}, plot1, plot2}, 
      plot1 = ContourPlot[ϕ, {x, -2, 2}, {y, -2, 2}, 
        ContourShading -> False, DisplayFunction -> Identity]; 
      plot2 = VectorPlot[Efield, {x, -2, 2}, {y, -2, 2}, 
        VectorScale -> Small, DisplayFunction -> Identity]; 
      Show[plot1, plot2, DisplayFunction -> $DisplayFunction]]

ϕ = 1/Sqrt[x^2 + (y - 0.5)^2] - 1/Sqrt[x^2 + (y + 0.5)^2];
plot[ϕ]

This is my output:

Output

However the plot supposed to look like this:

enter image description here

Why is my output so different and how can I fix it?

I have been studying notes from an undergrad course that used Mathematica 5, so my knowledge of it is rather outdated.

$\endgroup$
  • $\begingroup$ try StreamPlot instead of VectorPlot However, it seems unlikely that you get the desired plot since you have maxima in the places that vectorplot correctly shows but your "supposed" plot omits. $\endgroup$ – tsuresuregusa May 11 '17 at 23:44
  • $\begingroup$ @tsuresuregusa Then what might be wrong with VectorPlot for this problem? $\endgroup$ – Αλέξανδρος Ζεγγ Mar 11 at 14:43
9
$\begingroup$

Thanks for tsuresuregusa's advice, I changed VectorPlot to StreamPlot. It produced the correct output (which is the electric field of a dipole).

plot[ϕ_] := 
 Module[{Efield = -{D[ϕ, x], D[ϕ, y]}, plot1, plot2}, 
  plot1 = ContourPlot[ϕ, {x, -2, 2}, {y, -2, 2}, 
    ContourShading -> False, DisplayFunction -> Identity]; 
  plot2 = StreamPlot[Efield, {x, -2, 2}, {y, -2, 2}, 
    VectorScale -> Small, DisplayFunction -> Identity]; 
      Show[plot1, plot2, DisplayFunction -> $DisplayFunction]]
ϕ = 1/Sqrt[x^2 + (y - 0.5)^2] - 1/Sqrt[x^2 + (y + 0.5)^2];
plot[ϕ]

enter image description here

$\endgroup$
  • $\begingroup$ Since you mentioned that you were adapting version 5 code, here's a modern version of your code: plot[ϕ_] := Show[ContourPlot[ϕ, {x, -2, 2}, {y, -2, 2}, ContourShading -> False], StreamPlot[-D[ϕ, {{x, y}}] // Evaluate, {x, -2, 2}, {y, -2, 2}, VectorScale -> Small]] $\endgroup$ – J. M. will be back soon May 11 '17 at 23:58
  • $\begingroup$ Thank you J.M. The piece of code I used were for demonstrating modular programming, I guess it was actually unnecessary in this case. $\endgroup$ – Henry Wang May 12 '17 at 0:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.