0

I'm trying to map population in California counties for 2019. Using class() I saw the data is stored as characters so I changed it to numeric to get accurate results for summary(). When mapping, the values are being separated in an incorrect order (see legend). Not sure how else to solve this!

camap <- readOGR("CA_Counties_Pop2019.shp")
camap <- spTransform(camap, CRS("+init=epsg:4326"))

pop2019 <- as.numeric(as.character(camap$POP_2019))
summary(pop2019)

camap$poprange[pop2019 >= 1000 & pop2019 < 100000] <- "1,000-100,000"
camap$poprange[pop2019 >= 100000 & pop2019  < 500000] <- "100,000-500,000"
camap$poprange[pop2019 >= 500000 & pop2019  < 1000000] <- "500,000 - 1,000,000"
camap$poprange[pop2019 >= 1000000 & pop2019  < 5000000] <- "1,000,000 - 5,000,000"
camap$poprange[pop2019 >= 5000000 & pop2019  < 11000000] <- "5,000,000 - 11,000,000"

tm_shape(camap) + tm_fill("poprange", palette="Reds")`
  • The map:

enter image description here

lovalery
  • 4,524
  • 3
  • 14
  • 28
  • You need to define the "pop range" column as a factor in the desire order. There are many questions here demonstrating the question. – Dave2e Feb 24 '22 at 22:59
  • i've been testing out the factor stuff but i'm fairly new to R and don't understand how it could apply to my scenario? how can i use that to define ranges for each category like 1,000 - 100,000? – horriblecartographer Feb 24 '22 at 23:14
  • 1
    Here is a simple example: `factor(c("Fri", "Wed", "Mon"), levels=c("Mon", "Tue", "Wed", "Thur", "Fri"))` the first vector is your vector of labels and then the levels option defines the ordering. Then it will plot in order. See this question: https://stackoverflow.com/questions/66722291/choosing-ordering-for-labels-in-geometric-bar-plot – Dave2e Feb 24 '22 at 23:18
  • 1
    To complete @Dave2e's comment, and perhaps make more concrete the use of the code he proposed just above, you can refer to this [post](https://stackoverflow.com/questions/68569749/how-to-change-the-order-of-legend-elements-in-tmap). Hope this helps. Cheers. – lovalery Feb 24 '22 at 23:27
  • these are helpful, however i seem to be getting errors. so would i just add the factor line in right before plotting? as in, should i keep everything else the same and just add that in? – horriblecartographer Feb 24 '22 at 23:57
  • Yes change to factors just before plotting. If you are still having problems then please edit your question and provide an update. – Dave2e Feb 25 '22 at 01:15
  • 1
    If you use `base::cut` to divide your categories instead of your series of `[pop2019 >= ... & pop2019 < ...]` this will already give an ordered factor as the output – Sarah Feb 25 '22 at 03:33

0 Answers0