Issue with intensities for Color Gradient in Vector Field with ggplot

15 views Asked by At

I am creating a vector field of a dynamic system using R. I'm following this example in the R cookbook. I have an issue where the arrows that I view as larger are not appearing red. They should have high "speed" which is being calculated as the euclidean norm of the vector.

I have not reviewed the data frame that much, but everything is being calculated in the below script.

library(ggplot2)
library(grid)

density = 18
x <- seq(0, 600, length.out = density)
y <- seq(0, 230000, length.out = density)

# Create a grid of points
grid <- expand.grid(x = x, y = y)

# Define your equations for dx/dt and dy/dt
dx_dt <- function(x, y) {
  return(0.25 * x * (1 - (x/ 500)) - 0.1 * (y / 150000)*x)
}

dy_dt <- function(x, y) {
  return(0.05 * y * (1- (y / 150000)) + 0.02 * (x/ 500)*y)
}

# Calculate the values of dx/dt and dy/dt at each grid point
dx <- dx_dt(grid$x, grid$y)
dy <- dy_dt(grid$x, grid$y)

# Calculate the speed of the vector
speed <- sqrt(dx^2+dy^2)

# Create data frame to plot with ggplot
df <- data.frame(x = grid$x, y = grid$y, dx = dx, dy = dy, speed = speed)

View(df)

# From R Graphics Cookbook 13.12 Creating a Vector Field 

ggplot(data = df, aes(x = x, y = y)) + 
  geom_segment(aes(xend = x + dx, yend = y + dy, colour = speed), 
    arrow = arrow(length = unit(0.2, "cm")), size = 1) + 
    scale_colour_gradient2(low = "blue", mid = "green",  high = "red", midpoint = 2000) + 
  geom_line(data = data.frame(x = c(0, 500), y = c(375000, 0)), aes(x, y)) + 
  geom_line(data = data.frame(x = c(0, 416.6666), y = c(150000, 200000)), aes(x, y))

Here is a view of the dataframe

  x y        dx dy     speed
1    0.00000 0  0.000000  0  0.000000
2   35.29412 0  8.200692  0  8.200692
3   70.58824 0 15.155709  0 15.155709
4  105.88235 0 20.865052  0 20.865052
5  141.17647 0 25.328720  0 25.328720
6  176.47059 0 28.546713  0 28.546713
7  211.76471 0 30.519031  0 30.519031
8  247.05882 0 31.245675  0 31.245675
9  282.35294 0 30.726644  0 30.726644
10 317.64706 0 28.961938  0 28.961938

How do i get longer arrows to appear red? Shorter arrows green etc.

Larger X direction arrows are still green

Tried to calculate euclidean norm of each vector and map this speed variable to the aesthetic color using the scale_colour_gradient2.

0

There are 0 answers