Reputation: 3774
I have a csv file with latitude, longitude, and radiation. The data looks like a grid and there about 100 points across the state. I know there are a lot of R mapping options out there, but it seems easiest to take what I have and try to make a gradient from point to point, so it looks like a heat map. All of the heat map options I see work off of density and don't look accurate when I use them with these data. Is there a function I can use to smooth out the colors between points?
Here is a reproducible example with a much smaller range of numbers:
lat lon value
40.5 -91.5 4513619
41.0 -95.5 4490658
41.5 -96.0 4453810
41.5 -94.5 4475373
42.0 -95.5 4432107
42.0 -94.5 4416015
ggplot(df, aes(x = lon, y = lat, color = value)) +
geom_point(size=8) +
coord_equal() +
xlab('Longitude') +
ylab('Latitude')
Upvotes: 2
Views: 454
Reputation: 39174
We can use geom_tile
from the ggplot2
package to create a heatmep.
library(ggplot2)
ggplot(df, aes(x = lon, y = lat, fill = value)) +
geom_tile(color = "black") +
scale_fill_viridis_c() +
coord_equal() +
xlab('Longitude') +
ylab('Latitude') +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank())
Since you only provided six data points, the plot looks strange. Below I completed and expand your example dataset, and then use the same code to plot the data.
library(dplyr)
library(tidyr)
set.seed(123)
df2 <- df %>%
complete(lat, lon = seq(-96, -91.5, by = 0.5)) %>%
mutate(value = ifelse(is.na(value), sample(df$value, n(), replace = TRUE), value))
ggplot(df2, aes(x = lon, y = lat, fill = value)) +
geom_tile(color = "black") +
scale_fill_viridis_c() +
coord_equal() +
xlab('Longitude') +
ylab('Latitude') +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank())
Finally, since you are working with a spatial dataset, let's just convert the data to raster and plot it using the mapview
package.
library(sp)
library(sf)
library(raster)
library(mapview)
df_sp <- df2 %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
as("Spatial")
r <- raster(ncol = 10, nrow = 4)
extent(r) <- extent(df_sp)
r <- rasterize(df_sp, r, df_sp$value)
mapview(r)
DATA
df <- read.table(text = "lat lon value
40.5 -91.5 4513619
41.0 -95.5 4490658
41.5 -96.0 4453810
41.5 -94.5 4475373
42.0 -95.5 4432107
42.0 -94.5 4416015",
header = TRUE)
Upvotes: 1