I used Chatgpt to make a plot based on the following:
Using R, I want to create an array with 50×50 grid cells with 10 degrees spacing east-west (x coordinate) and 10 degrees north-south (y coordinate) extending from 20 degrees west to 40 degrees east and from 30 degrees north to 70 degrees north. I would like a plot that fills the grid cells with colors indicating the values. I want this plotted on top of a map showing country and coastal boundaries. The plot could be saved as a png file. I want the colors to be transparent (alpha=0.4).
I received the following code that works fairly ok, but when asking for another map projection (Lambert) that dont oversize the northern region so much, it fails sompletely. Is it not possible to use this way of plotting with e.g. Lambert proj?
”’
# Install and load necessary packages. Are already installed
#install.packages(c(“ggplot2”, “sf”, “rnaturalearth”, “rnaturalearthdata”))
library(ggplot2)
library(sf)
library(rnaturalearth)
library(rnaturalearthdata)
# Define the grid parameters
x_range <- seq(-20, 40, length.out = 50)
y_range <- seq(30, 70, length.out = 50)
# Create a data frame with grid coordinates
df <- expand.grid(lon = x_range, lat = y_range)
df$value <- runif(nrow(df), min = 0, max = 100) # Assign random values to each grid cell
# Prepare the world map data
world <- ne_countries(scale = "medium", returnclass = "sf")
# Plot the data
plot <- ggplot() +
geom_tile(data = df, aes(x = lon, y = lat, fill = value), alpha = 0.4) +
scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 50,
name = "Value", guide = guide_colorbar(barwidth = 10, barheight = 0.5)) +
geom_sf(data = world, fill = NA, color = "black") + # Add country boundaries
coord_sf(xlim = c(-20, 40), ylim = c(30, 70), expand = FALSE) +
theme_minimal(base_family = "sans") +
theme(
plot.background = element_rect(fill = "white"),
text = element_text(color = "black"),
axis.title = element_blank(), # Remove axis titles
axis.text = element_text(color = "black"),
legend.position = "bottom" # Position the legend at the bottom
) +
labs(title = "Geographical Map with Grid Cell Values")
# Save the plot as a PNG file with custom width and height
ggsave("map_plot.png", plot = plot, width = 10, height = 8, dpi = 300)
”’
produced plot