Hi,
My issue is that I want to use geom_tile in order to plot the values of a function with 2 variables. But the filling is really strange. If you look at the plot, in the left-upper corner there is a line, and every point above that line get the same value (at about y > 10). The more funny thing, is that the true values arent equal (sorry for the long reprex), but even if I change the invtervalls, the position of this "bound" changes.
library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.3
#> Warning: package 'ggplot2' was built under R version 3.6.3
#> Warning: package 'tibble' was built under R version 3.6.3
#> Warning: package 'tidyr' was built under R version 3.6.3
#> Warning: package 'dplyr' was built under R version 3.6.3
#> Warning: package 'forcats' was built under R version 3.6.3
f0 <- function(x) x[1]^2+x[2]^2
f1 <- function(x) x[1] + x[2]*2 - 5
L <- Rsolnp::solnp(pars = c(0,0), fun = f0, eqfun = f1, eqB = 0)
#>
#> Iter: 1 fn: 6.2407 Pars: 1.38572 2.07858
#> Iter: 2 fn: 5.0000 Pars: 1.00000 2.00000
#> Iter: 3 fn: 5.0000 Pars: 1.00000 2.00000
#> solnp--> Completed in 3 iterations
interval.x <- c(-10,10)
interval.y <- c(-10,10)
f <- function(x) {
y <- f0(x)
if (f1(x) > 0) y <- NA
return(y)
}
df <- expand.grid(c(seq(from = interval.x[1], to = interval.x[2], length.out = 100), L$pars[1]),y = c(seq(from = interval.y[1], to = interval.y[2], length.out = 100), L$pars[1])) %>% setNames(c("x", "y"))
z <- vector()
for (i in seq_along(df$x)) {
z[i] <- f(as.numeric(df[i,]))
}
df$z <- z
df <- df %>% transmute(
xmin = x - mean(unique(sort(df$x))[2],unique(sort(df$x))[3]),
xmax = x + mean(unique(sort(df$x))[2],unique(sort(df$x))[3]),
ymin = y - mean(unique(sort(df$y))[2],unique(sort(df$y))[3]),
ymax = y + mean(unique(sort(df$y))[2],unique(sort(df$y))[3]),
z = z
)
df <- df %>% filter(!is.na(z))
pp <- df %>% ggplot(aes(xmin = xmin, ymin = ymin, xmax = xmax, ymax = ymax, fill = z)) +
geom_vline(xintercept = L$pars[1]) +
geom_hline(yintercept = L$pars[2]) +
geom_rect(alpha = 0.3) + scale_fill_gradient(low = "blue", high = "red")
pp
Created on 2020-09-12 by the reprex package (v0.3.0)
I thing the problem can be somewhere with the fill method, but I don't know how to solve it.
Thank you for your help in advance,
Marcell