geom_density2d plot population data in r - r

I really need some help. I would like create an plot in R, but i do not know how should weight the point. I used this code below, and the point is equivalent. I would like is one of much bigger than another.
library(ggplot2)
library(ggmap)
Cau_map <- get_map(location='Caucasus', maptype="satellite", zoom = 5)
Cau <- data.frame(
lat = c(41.1057, 38.2968),
lon = c(44.2105, 47.1744),
data = c(52, 7)
)
ggmap(Cau_map, extent='device') +
geom_density2d(data=Cau, aes(x=lon, y=lat), color = "red", size=.3) +
stat_density2d(data=Cau, aes(x=lon, y=lat, fill = ..level.., alpha = ..level..), size = 0.08, bins = 6, geom = 'polygon')+
scale_fill_gradient(low = "red", high = "red4", guide=FALSE) + scale_alpha(range = c(0, 1), guide = FALSE)
This is what I got:

Related

Create animation or GIF with point plots in R

I am trying to create an animation or GIF that shows the evolution of an environmental condition over time. Basically, I have a dataset (example below) with year, value of the environmental condition, unit, and coordinates.
year
condition
unit
Lat
Long
1945
-0.120148
TSS
41.36531
41.67889
1948
0.274646
TSS
30.45368
-87.99042
1948
0.074794
TSS
30.45368
-87.99042
1975
-0.102050
TSS
38.10541
-122.06782
1979
-0.169886
NTU
29.77048
-84.91630
Complete dataset: https://drive.google.com/file/d/1XQ95KP_x-kbq_wdmpfpCiOonF-RoFsU1/view?usp=sharing
I am using ggplot2 to create the plots comprising year gaps. Here is the code I am using to plot the variation from 1945 to 1980:
`ggplot() +
geom_map(data = world, map = world,aes(long, lat, map_id = region),color = "seashell2", fill = "seashell", size = 0.3, alpha=0.9)+
geom_point(data = mapa_variacao_anual_45_80,aes(Long, Lat, color = med_turb),size=2, shape=16, position = position_jitter(width = 8)) +
labs(title = "1945 to 1980")+
theme(plot.title = element_text(hjust = 0.5))+
scale_colour_gradient( low = "darkgreen", high = "red")+
xlab("Longitude") + ylab("Latitude")+
theme(legend.title= element_blank())+
theme(panel.background = element_rect(fill = 'aliceblue', colour = 'gray'))`
My plan is to have several plots with determined year ranges and in the end combine all of them in sequence to show temporal variation.
Is there an easy way to combine the plots? I have been looking for solutions online but they seem not to suit my goal or are just too complicated.
Thanks in advance for any help.
You could get gganimate to handle the animation for you:
library(ggplot2)
library(gganimate)
world <- map_data("world")
mapa_variacao_anual_45_80$frames <- as.numeric(
factor(mapa_variacao_anual_45_80$year))
p <- ggplot() +
geom_map(data = world, map = world,
aes(long, lat, map_id = region),
color = "seashell2", fill = "seashell", size = 0.3, alpha = 0.9)+
geom_point(data = mapa_variacao_anual_45_80,
aes(Long, Lat, color = med_turb),
size = 2, shape = 16, position = position_jitter(width = 8)) +
labs(title = "1945 to 1980")+
theme(plot.title = element_text(hjust = 0.5))+
scale_colour_gradient( low = "darkgreen", high = "red") +
geom_text(data = mapa_variacao_anual_45_80,
aes(x = -180, y = 65, label = year), hjust = 0, size = 8,
check_overlap = TRUE) +
xlab("Longitude") +
ylab("Latitude")+
theme(legend.title= element_blank())+
theme(panel.background = element_rect(fill = 'aliceblue', colour = 'gray')) +
transition_events(mapa_variacao_anual_45_80$frames,
enter_length = 1, exit_length = 1)
anim_save("map.gif", p, device = "ragg_png", duration = 20, fps = 30,
width = 900, height = 450)
You can create a series of png files and assemble them into an animation with the gifski package:
library(ggplot2)
library(gifski)
for(i in 1:30){
gg <- ggplot(......)
ggsave(sprintf("myplot%03d.png", i), gg)
}
png_files <- Sys.glob("myplot*.png")
gifski(
png_files,
"myanimation.gif",
width = 400, height = 400,
delay = 1/5 # 5 images per second
)
file.remove(png_files)

White fill in the legends of the bubble maps in R using ggplot?

I'm posting this quite stupid question after unsuccessfully googleing for a while.
I have the following situation:
dta1 <- data.frame(LON = runif(20)*100, LAT = runif(20)*100, VALUE = runif(20)*10)
dta2 <- data.frame(LON = runif(20)*100, LAT = runif(20)*100, VALUE = runif(20)*10)
ggplot() +
geom_point(data=dta1, color = "blue", alpha = 0.5, aes(x=LON, y=LAT, size = VALUE)) +
geom_point(data=dta2, color = "red", alpha = 0.5, aes(x=LON, y=LAT, size = VALUE))
Which yields something like this (points' positions and sizes can change, it does not matter):
The result is quite good, but I want the circles in the legend to be draw with black borders and filled with white.
Any idea?
Would this be an acceptable result?
I supposed your point was to make the size legend of an anonymous colour, unrelated to the blue or the red of the actual points.
set.seed(1)
dta1 <- data.frame(LON = runif(20)*100, LAT = runif(20)*100, VALUE = runif(20)*10)
dta2 <- data.frame(LON = runif(20)*100, LAT = runif(20)*100, VALUE = runif(20)*10)
library(ggplot2)
ggplot() +
geom_point(data=dta1, alpha = 0.5, aes(x=LON, y=LAT, size = VALUE, colour = "value1")) +
geom_point(data=dta2, alpha = 0.5, aes(x=LON, y=LAT, size = VALUE, colour = "value2")) +
scale_color_manual(values = c(value1 = "blue", value2 = "red"))
Alternately, closely related to the "fill" answer:
library(ggplot2)
ggplot() +
geom_point(data = dta1, shape = 21, alpha = 0.5, aes(x = LON, y = LAT, size = VALUE, fill = "value1")) +
geom_point(data = dta2, shape = 21, alpha = 0.5, aes(x = LON, y = LAT, size = VALUE, fill = "value2")) +
scale_fill_manual(values = c(value1 = "blue", value2 = "red")) +
theme_light() +
guides(fill = FALSE)
Hmm. I dont know of a way of changing something in the legend only. In a way thats contrary to the point of the legend. This is the best i got.
library(ggplot2)
dta1 <- data.frame(LON = runif(20)*100, LAT = runif(20)*100, VALUE = runif(20)*10)
dta2 <- data.frame(LON = runif(20)*100, LAT = runif(20)*100, VALUE = runif(20)*10)
ggplot() +
geom_point(data=dta1, color = "blue", alpha = 0.5,shape = 21, aes(x=LON, y=LAT, size = VALUE)) +
geom_point(data=dta2, color = "red", alpha = 0.5,shape = 21, aes(x=LON, y=LAT, size = VALUE)) +
theme_classic()
Created on 2020-12-09 by the reprex package (v0.3.0)
Alternatively, it could be something like this:
dta1$C <- 1
dta2$C <- 2
dta1 <- rbind(dta1, dta2)
ggplot(dta1, aes(x = LON, y = LAT, size = VALUE, fill = C)) +
geom_point(shape=21)
Which yields:
But without the inferior (rectangle titled "C") part of the legend.

How do I add a legend using aes, ggplot2 and maps?

I'm trying to make a map with points plotted for the Canadian prairie provinces, but I'm having no luck adding in a legend to my map. I'm very new to mapping in r, so I'm not understanding how I should include aes to get a legend. My data for siteDataTrees is from an excel csv file and the top looks like this:
siteDataTrees
and the data for siteDataBoth is also from a csv file and the top looks like this:
siteDataBoth.
Here's what I have so far for my code:
library(maps)
library(ggplot2)
library(sf)
prairies1 <- map("worldHires","Canada", xlim = c(-120,-87), ylim = c(49,61),
plot = FALSE, fill = TRUE)
prairies <- st_as_sf(prairies1)
ggplot(data = prairies) +
geom_sf() +
geom_point(data = siteDataTrees, aes(x = long, y = lat), size = 2.5, pch = 21,
fill = "purple", show.legend = TRUE) +
geom_point(data = siteDataBoth, aes(x = long, y = lat), size = 2.5, pch = 21,
fill = "light green", show.legend = TRUE) +
geom_text(data = locations, aes(x = long, y = lat, label = name),
size = 2, col = "black", check_overlap = FALSE) +
annotation_scale(location = "tr", width_hint = 0.2) +
ggtitle("Climate Stations and Tree Chronology Locations for South AB") +
labs(x = "latitude", y = "longitude") +
theme(legend.position = "right") +
coord_sf(xlim = c(-115, -110), ylim = c(48.9, 50.49), expand = FALSE)
I've also included a map to show what it looks like without the legend.
How should I take the data frame prairies and use it with aes to include a legend? Is there another way to add in a legend in ggplot2 without using the aes function? Thank you in advance for your help and please let me know if something is missing as this is my first posting
Let me give you a couple of examples on how to work out a legend using a slightly modified example from r-spatial.
First we prepare the data:
library(maps)
library(ggplot2)
library(sf)
library(rnaturalearth)
library(rnaturalearthdata)
world <- ne_countries(scale = "medium", returnclass = "sf")
(sites <- data.frame(longitude = c(-80.144005, -80.109),
latitude = c(26.479005,26.83),
type = c("tree", "station")))
Now we plot. Case 1: color is not an issue
ggplot(data = world) +
geom_sf() +
geom_point(data = sites,
aes(x = longitude, y = latitude, fill = type),
size = 4,
shape = 23) +
coord_sf(xlim = c(-88, -78), ylim = c(24.5, 33), expand = FALSE) +
theme(legend.position = "bottom")
Case 2: fill color is an issue.
Here we can use a named vectors to pass the colors and the labels we want by type of point. For example:
mapfill <- c('tree' = "forestgreen", 'station' = "purple")
maplab <- c('tree' = "trees in prairies", 'station' = "Stations in prairies")
Then we plot combining both mapfill and maplab:
ggplot(data = world) +
geom_sf() +
geom_point(data = sites, aes(x = longitude, y = latitude, fill = type), size = 4,
shape = 23) +
scale_fill_manual(values = mapfill, labels = maplab) +
coord_sf(xlim = c(-88, -78), ylim = c(24.5, 33), expand = FALSE) +
theme(legend.position = "bottom")
Remark 1 If you do not want type in the legend title you can either delete it using legend. title = element_blank() within theme
Remark 2 If, instead of fill, you are using color, use function scale_color_manual. If you are combining both fill and color do the same with scale_***_manual
In spirit of full disclosure, if you do not mind the colors and you want a quick fix (and I cannot stress this enough) you can also code fill = "TextYouWantInLegend" within aes. See following example:
ggplot(data = world) +
geom_sf() +
geom_point(data = sites[1,], aes(x = longitude, y = latitude, fill = "toto"), size = 4,
shape = 23) +
geom_point(data = sites[2,], aes(x = longitude, y = latitude, fill = "koko"), size = 4,
shape = 23) +
coord_sf(xlim = c(-88, -78), ylim = c(24.5, 33), expand = FALSE) +
theme(legend.position = "bottom")

How to use several symbols, colour, and fill in ggmap without changing the legend colour in R?

I'm using ggmap to plot some filled points across the ocean but they overlap so I used colour=black to give them an outline. When I use pch=21 the legend doesn't change and the points are outlined in black like I want. But, I am trying to get 3 different symbols on the map as well. When I specify the different symbols my points in the legend all turn black.
Here is some sample data and the code I used to get the map with the correct legend but wrong symbols
#library
library(ggmap)
library(mapdata)
library(ggplot2)
#sample
mapoc_temp = data.frame(longitude= c(-64.5, -63.1, -62.4, -62.2, -66.0, -61.9),
latitude= c(42.7, 44.8, 45.8, 45.6, 43.0, 40.2),
Zone = sample(c(1,4,6,7), 6, replace = T),
location = sample(c(1,2,3), 6, replace = T))
#map
canada = map_data("worldHires")
ggplot(data = canada) +
borders("world", xlim = c(-130, -60), ylim = c(20, 50), colour = "black", fill = "grey50") +
geom_polygon(data = canada, aes(x=long, y = lat, group = group), fill = "grey50") +
#coordinates of my map
coord_sf(xlim=c(-84, -41), ylim=c(24,51), expand = FALSE) +
#map the receiver locations
geom_point(data = mapoc_temp,
mapping = aes(x = longitude,
y = latitude,
fill = Zone),
pch = 21,
size = 15, colour = "black") +
#fill the zones
scale_color_manual(values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) +
scale_fill_manual(values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361"))
and this is what the map looks like
When I try to add the symbols, I get the correct symbols but my legend isn't correct anymore. Below is the code and image.
ggplot(data = canada) +
borders("world", xlim = c(-130, -60), ylim = c(20, 50), colour = "black", fill = "grey50") +
geom_polygon(data = canada, aes(x=long, y = lat, group = group), fill = "grey50") +
#coordinates of my map
coord_sf(xlim=c(-84, -41), ylim=c(24,51), expand = FALSE) +
#map the receiver locations
geom_point(data = mapoc_temp,
mapping = aes(x = longitude,
y = latitude,
fill = as.factor(Zone)),
pch = pch = if_else(mapoc_temp$location == 1,25,
if_else(mapoc_temp$location == 3, 23, 21)),
size = 15, colour = "black") +
scale_x_continuous(label = abs) +
scale_y_continuous(label = abs) +
#fill the zones in with viridis
scale_color_manual(values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) +
scale_fill_manual(values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361"))
Does anyone know how to fix the legend in the second image so that the points are the correct colours? I don't need the symbols to be in the legend
Actually, your issue is due to a bug described here: https://github.com/tidyverse/ggplot2/issues/2322.
To go over, you can do:
ggplot(data = canada) +
borders("world", xlim = c(-130, -60), ylim = c(20, 50), colour = "black", fill = "grey50") +
geom_polygon(data = canada, aes(x=long, y = lat, group = group), fill = "grey50") +
#coordinates of my map
coord_sf(xlim=c(-84, -41), ylim=c(24,51), expand = FALSE) +
#map the receiver locations
geom_point(inherit.aes = FALSE, data = mapoc_temp,
mapping = aes(x = longitude,
y = latitude,
fill = factor(Zone),
shape = factor(location)),
size = 5) +
scale_x_continuous(label = abs) +
scale_y_continuous(label = abs) +
#fill the zones in with viridis
scale_fill_manual(name = "Zone", values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361"), breaks = c("1","4","6","7")) +
scale_shape_manual(values = c("1" = 21, "2" = 22, "3" = 24))+
guides(fill = guide_legend(override.aes=list(shape=21)), shape = FALSE)
As mentioned by #Edward, you can get rid of the shape legend by adding guides(shape = FALSE).
Does it answer your question ?
I don't have your data, so I will use the good ol' mtcars dataset. The trick is to assign the shapes manually, otherwise, ggplot will complain "A continuous variable can not be mapped to shape".
mtcars$shape <- ifelse(mtcars$cyl==4, 21, ifelse(mtcars$cyl==6, 23, 25))
ggplot(mtcars, aes(wt, mpg)) +
geom_point(aes(fill = factor(cyl), shape=factor(cyl)), col="black", size=3) +
scale_shape_manual(values=c(21,23,25))
For your own data, try:
mapoc_temp$shape <- factor(mapoc_temp$location + 20)
geom_point(data = mapoc_temp,
mapping = aes(x = longitude,
y = latitude,
fill = factor(Zone),
shape= shape),
size = 15, colour = "black") +
scale_shape_manual(values=c(21,22,23)) + # Must be same length as unique location.
guides(shape=FALSE) + # If you don't want an extra shape legend.
guides(fill = guide_legend(override.aes=list(shape=21))) # A necessary fudge

scale_color_gradientn() not producing the correct output

I am having trouble using ggmap + ggplot to create a plot with a custom grid. Here is the plotting code that I am using with some quickly generated sample data. It successfully generates a plot but ignores my custom colors in scale_color_gradientn(). Any suggestions would be greatly appreciated!
library(ggplot2)
library(reshape2)
library(ggmap)
Lon <- runif(100, -100, -92)
Lat <- runif(100, 34, 45)
Conc <- runif(100, 1, 8)
JECeGRIDLoc <- c(39.2865, -96.1172)
PlotModel1 <- data.frame(Lat, Lon, Conc)
### What I need ###
al1 = get_map(location = c(lon = JECeGRIDLoc[2], lat = JECeGRIDLoc[1]), zoom
= 06, maptype = 'satellite')
al1MAP = ggmap(al1)
al1MAP + geom_tile(data = PlotModel1, aes(x = Lon, y = Lat, fill = Conc)) +
scale_fill_gradient(limits=c(min(min(PlotModel1$Conc),
min(PlotModel2$Conc)),
max(max(PlotModel1$Conc), max(PlotModel2$Conc))), low = "yellow", high =
"red") +
scale_color_gradientn(colors = c("purple", "red", "orange", "yellow",
"green")) +
xlab("Longitude") +
ylab("Latitude") +
ggtitle("Jeffrey Energy Center (2012): \n eGRID Model Dispersion Area")
### Additional example (does not work) ###
ggplot(data = PlotModel1, aes(x = Lon, y = Lat, fill = Conc)) +
geom_point() +
scale_color_gradientn(colors = c("purple", "red", "orange", "yellow",
"green"))
Swap fill to colour and it works
ggplot(data = PlotModel1, aes(x = Lon, y = Lat, colour = Conc)) +
geom_point() +
scale_color_gradientn(colors = c("purple", "red", "orange", "yellow",
"green"))

Resources