I'm trying to use ggplot to make a contour plot of some weather data. I'm trying to graph the contents of the following dataframe:
dt
-18.25 -17.75 -17.25 -16.75 -16.25
-67.25 -1.042116 -0.2610118 3.527539 1.698116 5.8457116
-66.75 10.888635 10.7380880 5.282561 10.558529 12.0000000
-66.25 11.793157 -0.1322045 12.000000 12.000000 12.0000000
-65.75 9.407542 11.4077278 12.000000 12.000000 -0.6859424
-65.25 6.355656 9.4592526 12.000000 -2.770040 -4.0922426
-64.75 3.103860 12.0000000 3.928329 -5.728103 -5.2666501
-64.25 6.720593 10.5359569 -2.267352 -7.223494 -6.5408307
Here, column names are the latitude and the rownames are the longitude.
> lon
[1] -67.75 -67.25 -66.75 -66.25 -65.75 -65.25 -64.75 -64.25 -63.75
> lat
[1] -18.75 -18.25 -17.75 -17.25 -16.75 -16.25 -15.75
And the values in the dataframe are the ones I want to contour in eaxh coordinate.
In order to graph this, I'm using the following function:
ggplot(dt)
geom_density_2d_filled(aes(x=rownames(dt),y=names(dt)))
But whenever I try to do yhis, I get the following error:
Error in check_aesthetics()
:
! Aesthetics must be either length 1 or the same as the data (7): y
I would really appreciate any insights to solve this problem!
CodePudding user response:
You have vectors with different length. Therefore bring them to the same length and plot:
Update with the original data:
library(tidyverse)
lon <- c(-67.75, -67.25, -66.75, -66.25, -65.75, -65.25, -64.7, 5 -64.25, -63.75)
lat <- c(-18.75, -18.25, -17.75, -17.25, -16.75, -16.25, -15.75)
x <- lon
y <- lat
max.len = max(length(x), length(y))
x = c(x, rep(NA, max.len - length(x)))
y = c(y, rep(NA, max.len - length(y)))
tibble(x,y) %>%
ggplot(aes(x, y))
geom_density_2d()
First answer:
library(tidyverse)
x <- colnames(dt)
y <- rownames(dt)
max.len = max(length(x), length(y))
x = c(x, rep(NA, max.len - length(x)))
y = c(y, rep(NA, max.len - length(y)))
tibble(x,y) %>%
mutate(x = parse_number(x)) %>%
mutate(y = as.numeric(y)) %>%
ggplot(aes(x, y))
geom_density_2d()
data:
x <- c("18.25", "17.75", "17.25", "16.75", "16.25")
y <- c("-67.25", "-66.75", "-66.25", "-65.75", "-65.25", "-64.75", "-64.25")