I am trying to visualize the data on a map by using ggplot2
I follow the instruction on this website:https://socviz.co/maps.html. I imitate the example of gun-related suicide.
Code is as followed:
cancer$rate_cut=cut(cancer$rate,c(5,10,15,20,25,30))
county_map %>% sample_n(5)
orange_pal <- RColorBrewer::brewer.pal(n = 6, name = "Oranges")
orange_pal
## [1] "#FEEDDE" "#FDD0A2" "#FDAE6B" "#FD8D3C" "#E6550D"
## [6] "#A63603"
orange_rev <- rev(orange_pal)
orange_rev
## [1] "#A63603" "#E6550D" "#FD8D3C" "#FDAE6B" "#FDD0A2"
## [6] "#FEEDDE"
can_p <- ggplot(data = county_full,
mapping = aes(x = long, y = lat,
fill = cancer$rate_cut,
group = group))
can_p1 <- can_p + geom_polygon(color = "gray90", size = 0.05) + coord_equal()
can_p2 <- can_p1 + scale_fill_manual(values = orange_pal)
can_p2 + labs(title = "Gun-Related Suicides, 1999-2015",
fill = "Rate per 100,000 pop.") +
theme_map() + theme(legend.position = "bottom")
My data looks like this:
head(county_full)
long lat order hole piece group id county_name rate
1 1225889 -1275020 1 FALSE 1 0500000US01001.1 01001 <NA> NA
2 1235324 -1274008 2 FALSE 1 0500000US01001.1 01001 <NA> NA
3 1244873 -1272331 3 FALSE 1 0500000US01001.1 01001 <NA> NA
4 1244129 -1267515 4 FALSE 1 0500000US01001.1 01001 <NA> NA
5 1272010 -1262889 5 FALSE 1 0500000US01001.1 01001 <NA> NA
6 1276797 -1295514 6 FALSE 1 0500000US01001.1 01001 <NA> NA
count population rate_cut
1 NA NA <NA>
2 NA NA <NA>
3 NA NA <NA>
4 NA NA <NA>
5 NA NA <NA>
6 NA NA <NA>
Although here it is all NA, I do have the data below.
When I ran the code, R gave me an error message:
Error: Aesthetics must be either length 1 or the same as the data (191382): fill
Run `rlang::last_error()` to see where the error occurred.
> rlang::last_error()
<error/rlang_error>
Aesthetics must be either length 1 or the same as the data (191382): fill
Backtrace:
1. (function (x, ...) ...
2. ggplot2:::print.ggplot(x)
4. ggplot2:::ggplot_build.ggplot(x)
5. ggplot2:::by_layer(function(l, d) l$compute_aesthetics(d, plot))
6. ggplot2:::f(l = layers[[i]], d = data[[i]])
7. l$compute_aesthetics(d, plot)
8. ggplot2:::f(..., self = self)
9. ggplot2:::check_aesthetics(evaled, n)
========================================================
Thanks for the comment and I modified the code by joining the data(cancer and county_map).I get the map but I also got a warning message.
The latest code is like this:
can_p <- ggplot(data = county_full,
mapping = aes(x = long, y = lat,
fill = county_full$rate_cut,
group = group))
can_p1 <- can_p + geom_polygon(color = "gray90", size = 0.05) + coord_equal()
can_p2 <- can_p1 + scale_fill_manual(values = orange_pal)
can_p2 + labs(title = "Cancer incidence, 1999-2015",
fill = "Rate per 100,000 pop.") +
theme_map() + theme(legend.position = "bottom")
Warning message:Use of `county_full$rate_cut` is discouraged. Use `rate_cut` instead.