Reproducible R code
library(ggplot2)
library(metR)
v <- reshape2::melt(volcano)
g <- ggplot(v, aes(Var1, Var2))
geom_contour(aes(z = value), color = "white", size = 1.25,
breaks = c(100, 110, 120, 130, 140, 150, 160, 170, 180, 190))
geom_contour(aes(z = value, linetype = ifelse(value <= 130, "solid", "dash")),
color = "black", size = 0.45,
breaks = c(100, 110, 120, 130, 140, 150, 160, 170, 180, 190),
show.legend = F)
geom_text_contour(aes(z = value))
g
When I overlay a geom_contour
with a white background and another geom_contour
with an ifelse
function for different line types depending on value, the plotting procedure shows broken contours, close to the specified ifelse value of 130, as shown in the plot below.
Can someone recommend a solution? I suspect it has to do with the interpolation method.
Reproducible code without the metR
library (used to plot contour labels on above plot)
library(ggplot2)
v <- reshape2::melt(volcano)
g <- ggplot(v, aes(Var1, Var2))
geom_contour(aes(z = value), color = "white", size = 1.25,
breaks = c(100, 110, 120, 130, 140, 150, 160, 170, 180, 190))
geom_contour(aes(z = value, linetype = ifelse(value <= 130, "solid", "dash")),
color = "black", size = 0.45,
breaks = c(100, 110, 120, 130, 140, 150, 160, 170, 180, 190),
show.legend = F)
g
CodePudding user response:
In short, there is no way to use ifelse
successfully with the geom.contour
function. The correct usage is by plotting both contours individually. Please note that the error is purely caused by your ifelse
function, not by overlaying two plots, as you assumed in your title.
library(reshape2)
library(ggplot2)
v <- reshape2::melt(volcano)
g <- ggplot(v, aes(Var1, Var2))
geom_contour(aes(z = value, linetype = "solid"),
color = "black", size = 0.45,
breaks = c(140, 150, 160, 170, 180, 190),
show.legend = F)
geom_contour(aes(z = value, linetype = "dashed"),
color = "black", size = 0.45,
breaks = c(100, 110, 120, 130),
show.legend = F)
g
But, I still wonder if there is a way to do this successfully with the ifelse
function?