Add new points into a contour plot in ggplot2 - r

I am trying to plot some extra points onto an existing contour plot with ggplot2:
require(ggplot2)
library(reshape2) # for melt
volcano3d <- melt(volcano)
names(volcano3d) <- c("x", "y", "z")
v <- ggplot(volcano3d, aes(x, y, z = z))
v <- v + stat_contour()
print(v)
newdata <- data.frame(x = runif(7)*60, y = runif(7)*60)
v <- v + geom_point(data=newdata, aes(x, y))
print(v)
The first print is ok, but the second is just blank. Why?

Related

labeling lines value in countour plot using ggplot2 in R [duplicate]

I wonder how to get data labels on lines in ggplot2 for contours. Thanks
require(grDevices) # for colours
x <- seq(-4*pi, 4*pi, len = 27)
y <- seq(-4*pi, 4*pi, len = 27)
r <- sqrt(outer(x^2, y^2, "+"))
rx <- range(x <- 10*1:nrow(volcano))
ry <- range(y <- 10*1:ncol(volcano))
ry <- ry + c(-1, 1) * (diff(rx) - diff(ry))/2
plot(
x = 0
, y = 0
, type = "n"
, xlim = rx
, ylim = ry
, xlab = ""
, ylab = ""
)
contour(
x = x
, y = y
, z = volcano
, add = TRUE
)
library(ggplot2)
library(reshape2)
volcano3d <- melt(volcano)
names(volcano3d) <- c("x", "y", "z")
# Basic plot
v <- ggplot(volcano3d, aes(x, y, z = z))
v + stat_contour()
using directlabels package and picking solution from this
# Basic plot
v <- ggplot(volcano3d, aes(x, y, z = z))
library(directlabels)
v2 <- v + stat_contour(aes(colour = ..level..))
direct.label(v2, method="bottom.pieces")
This is an old question already answered, but I do a lot of contour plots and I think that there is an easier and more versatile way to do this using the package metR (https://rdrr.io/github/eliocamp/metR/f/vignettes/Visualization-tools.Rmd). This package has the function geom_label_contour() that provides an easy way to plot labels of contours. Also provides a lot of functions to plot maps.
library(ggplot2)
library(reshape2)
library(metR)
volcano3d <- melt(volcano)
colnames(volcano3d) <- c('x','y','z')
ggplot(data = volcano3d, aes(x=x,y=y,z=z)) + geom_contour() +
geom_label_contour()

Cumulative Density Plots with ggplot and plotly

When we take the following example from ggplot2 docs
df <- data.frame(x = c(rnorm(100, 0, 3), rnorm(100, 0, 10)),
g = gl(2, 100))
library(ggplot2)
p <- ggplot(df, aes(x, colour = g)) +
stat_ecdf(geom = "step", na.rm = T) + # interchange point and step
theme_bw()
p
We can create a standard cdf plot. Now if we want to play with the plot in plotly, I obtain a very confusing image when I use the step command. See below. However, when I use the point command plotly behaves like it should. What is happening with the step command? Why can't I recreate the image from using ggplot only?
library(plotly)
ggplotly(p)
I found the solution here https://community.plotly.com/t/bug-with-ggplot2-stat-ecdf-function/1187/3.
You should reorder the dataframe along x.
df <- dplyr::arrange(df, x)
library(ggplot2)
p <- ggplot(df, aes(x, colour = g)) +
stat_ecdf(geom = "step", na.rm = T) +
theme_bw()
p
library(plotly)
ggplotly(p)
This can be solved using ecdf() function.
## ecdf function to get y and 1-y
rcdf <- function (x) {
cdf <- ecdf(x)
y1 <- cdf(x)
y <- unique(y1)
# xrcdf <- 1-y ## to get reverse cdf
xrcdf <- y ## to get cdf
}
ug <- unique(df$g)
ng <- length(ug)
xll <- min(df$x)
xul <- max(df$x)
adr <- data.frame(myxx=c(), myyy=c(), mygg=c())
lapply(1:ng, function(i){
ad2r <- subset(df, g==ug[i])
myx1 <- unique(ad2r$x)
myxx <- c(xll,myx1,xul) ## add lowest value - dummy to assign 100%
myy1 <- rcdf(ad2r$x)
# myyy <- c(1.0,myy1,0.0) ## add 100% to get reverse cdf
myyy <- c(0.0,myy1,1.0) ## add 0% to get cdf
mygg <- ug[i]
ad2rf <- data.frame(myxx,myyy,mygg)
adr <<- rbind(adr,ad2rf)
})
adf <- adr[order(adr$myxx),]
pp <- ggplot(data=adf,
aes_(x=adf$myxx, y=100*adf$myyy, col=adf$mygg, group=adf$mygg)) +
geom_step() +
labs(title="CDF", y = "Y", x = "X", col=NULL)
ppp <- ggplotly(pp, tooltip=c("x","y"))
ppp
This gives the following output:
CDF

ggplot2 + stat_contour variable binwidth

What I'm trying to do is to have a variable binwidth in a ggplot2 contour plot, that is the distance between the different "equi-level lines".
Here is a minimal working example from the documentation, with a constant binwidth:
# Generate data
library(reshape2) # for melt
volcano3d <- melt(volcano)
names(volcano3d) <- c("x", "y", "z")
# Basic plot
v <- ggplot(volcano3d, aes(x, y, z = z))
v + stat_contour(aes(colour=..level..), binwidth = 2)
Use the breaks argument, for example:
v <- ggplot(volcano3d, aes(x, y, z = z))
v + stat_contour(aes(colour= ..level..), breaks = c(100, 101, 102, 105, 110, 150, 175))

incorrect values of x, y axis using contour plot

I wanted to create a contour plot using the ggplot library. I checked the documentation on this topic, and found the code to get this done. Unfortunately the code uses the indexes of the matrix z storing the surface, as x and y. How do I change this to the actual value of x and y?
Below my code generating the contour plot.
objective_function <- function(vec) {
basin_function <- function(vec){
if(all(vec == 0)) {
return(0)
} else{
return(sum(exp(-2.0/vec^2)+sin(vec*pi*2)))
}
}
return(basin_function(vec))
}
objective_function_wrapper <- function(x_vec, y_vec) {
vec <-rbind(x_vec,y_vec)
return(apply(vec,2, objective_function))
}
plotSurf <-function(){
x <- y <-seq(from=-5, to =5, by=0.1)
z <- outer(x,y, objective_function_wrapper)
surf3d <- melt(z)
names(surf3d) <- c("x", "y", "z")
p1 <- ggplot(data=surf3d, aes(x=x, y=y, z=z))
p1 <- p1 + geom_tile(aes(fill=z))+stat_contour()
print(p1)
}
plotSurf()
You need to substitute the x- and y-values for the row and column numbers that are currently sitting in the "melt"-ed result of the outer call:
x <- y <-seq(from=-5, to =5, by=0.1)
z <- outer(x,y, objective_function_wrapper)
surf3d <- melt(z)
names(surf3d) <- c("x", "y", "z")
surf3d$x <- rep(x, ncol(z) ); surf3d$y <- rep(y, each=nrow(z) )

Custom levels in ggplot2 contour plot?

Here is a code snippet from the docs site:
# Generate data
library(reshape2) # for melt
volcano3d <- melt(volcano)
names(volcano3d) <- c("x", "y", "z")
# Basic plot
v <- ggplot(volcano3d, aes(x, y, z = z))
v + stat_contour(binwidth = 10)
Output:
What if I want to draw contour lines at custom levels? For example, in the volcano3d data set, I want these levels to be indicate: z == 120, 140, 160.
Replace binwidth= with argument breaks= and provide breakpoint you need.
ggplot(volcano3d, aes(x, y, z = z)) +
stat_contour(breaks=c(120,140,160))

Resources