Gustavo Sarturi
Gustavo Sarturi

Reputation: 61

How can I plot vector field on Julia?

I'm new on Julia and I've tried to make the code of following post How to plot a vector field in Julia?, but, didn't work, so, I would like to know if it's possible to plot with the package "Plots" and how? It'll be very important to my research.

P.s.: Someone gave to me the following code, but, actually, I don't know why isn't working:

using Plots
gr(size=(600,400))

function example()
  X = linspace(-2, 2, 100)
  Y = linspace(-2, 2, 100)
  f(x, y) = x^3 - 3x + y^2
  contour(X, Y, f)

  x = linspace(-2, 2, 11)
  y = linspace(-2, 2, 11)
  df(x, y) = [3x^2 - 3; 2y] / 25
  quiver!(x, y', quiver=df, c=:blue)

  xlims!(-2, 2)
  ylims!(-2, 2)
  png("example")
end

example()

Upvotes: 6

Views: 3085

Answers (3)

BuddhiLW
BuddhiLW

Reputation: 627

Updating the answer to Julia 1.6.3,

Helper function source: How to plot a vector field in Julia?

using Plots
gr(size=(600,400))

meshgrid(x, y) = (repeat(x, outer=length(y)), repeat(y, inner=length(x))) # helper function to create a quiver grid.

function example()
  X = range(-2, stop=2, length=100)
  Y = range(-2, stop=2, length=100)
  f(x, y) = x^3 - 3x + y^2
  Plots.contour(X, Y, f)

  xs,ys = meshgrid(range(-2, stop=2, length=11), range(-2,stop=2,length=11))
  df(x, y) = [3x^2 - 3; 2y] / 25
  quiver!(xs, ys, quiver=df, c=:blue)

  xlims!(-2, 2)
  ylims!(-2, 2)
  png("example")
end

example()

enter image description here

Upvotes: 2

wildart
wildart

Reputation: 97

For Plots v1.10.4, you need to provide a start position for every quiver

# same code as in above answer
quiver!(repeat(x,11), vec(repeat(y',11)), quiver=df, c=:blue)

Upvotes: 3

carstenbauer
carstenbauer

Reputation: 10127

As has already been said in the comments, you should provide error messages as well as people otherwise have to guess what's wrong with your code.

However, in your case I think I could guess it :)

On Julia 1.0 the following works:

using Plots
gr(size=(600,400))

function example()
  X = range(-2, stop=2, length=100)
  Y = range(-2, stop=2, length=100)
  f(x, y) = x^3 - 3x + y^2
  contour(X, Y, f)

  x = range(-2, stop=2, length=11)
  y = range(-2, stop=2, length=11)
  df(x, y) = [3x^2 - 3; 2y] / 25
  quiver!(x, y', quiver=df, c=:blue)

  xlims!(-2, 2)
  ylims!(-2, 2)
  png("example")
end

example()

and gives the following output

enter image description here

Note that I only changed all occurences of linspace to range(-2, stop=2, length=X) because the linspace function has been deprecated in Julia 0.7.

Upvotes: 12

Related Questions