Changing the text in legend in ggplot map R Studio

混江龙づ霸主 提交于 2019-12-06 09:24:41

The problem was that stateHeat was being read as a character instead of a number, and the discrete factor type ordered it 1, 10, 2, 3 ...

Therefore, we should reorder the factor, with fct_reorder and tell it we want 1 to 10 in proper numeric order.

library(maps)
#> Warning: package 'maps' was built under R version 3.5.2
library(ggplot2)

# Get all states data
all_states <- map_data("state")

# Get usheat data
q4_heatMap <- read.csv("https://download2261.mediafire.com/52r319zccrkg/jkz9ak66bj4sl24/q4_heatmap.csv")

# Clean the data
subHeat <- subset(q4_heatMap, WEEK=="4")
region <- tolower(subHeat$STATENAME)
stateHeat <- subHeat$ACTIVITY.LEVEL
stateHeat <- gsub('Level ', '', stateHeat)
usHeat <- data.frame(region,stateHeat)

# make sure stateHeat is in the correct data type (factor) and the levels are in the right order
library(forcats)
usHeat$stateHeat <- fct_relevel(stateHeat, as.character(1:10))
# check data type and factor level order 
levels(usHeat$stateHeat)
#>  [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

# Merge two set of dataframes
heatTotal <- merge(all_states, usHeat, by="region")

# heatColor
heatColor <- c("peru", "hotpink", "orchid", 
               "mediumpurple", "deepskyblue", "cyan3","mediumseagreen",
               "limegreen","darkkhaki","salmon")

# Plot
(usHeatMap <- ggplot(data = heatTotal) + 
    geom_polygon(aes(x = long, y = lat, fill = stateHeat, group = group)) + 
    coord_fixed(1.3) + 
    labs(title = "2018-19 Influenza Season Week 4",
         x = "Longitude", y="Latitude", color="Heat level"))

# labels and custom colors
usHeatMap + scale_fill_manual(labels=c("Extreme High","Middle High","Low High",
                                        "Moderate","Low Moderate","Higher Low","Low",
                                        "Minimal","Very Minimal","Extreme Minimal")
                      ,values = heatColor)

Created on 2019-02-28 by the reprex package (v0.2.1)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!