Get the legend ggplot2 to display the percent sign in r

The following is a reproducible example of the problem I'm trying to solve. In ggplot2, I created a bunch of useful maps, and everything is going well. Since I pointed percentages to data for use with geom_text, I would like to make a legend about geom_tile also to display percentages (I can only multiply the actual values โ€‹โ€‹by 100 right now). Ideally, I would like the legend panel on the right to show 8%, 4%, 0%, -4%, -8%.

#load in libraries require(plyr) require(dplyr) require(reshape2) require(ggplot2) require(scales) testDF <- structure(list(strategies = structure(c(8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L), .Label = c("Class 1", "Class 2", "Class 3", "Class 4", "Class 5", "Class 6", "Class 7", "Class 8"), class = "factor"), School1 = c(0.0355662887589396, 0.0316753241146625, 0.00606392341292672, 0.0250738342627283, -0.0405709181701368, 0.0237665074609996, 0.00587364885411765, -0.0343914002059331), School2 = c(NA, NA, NA, 0.0225535750673764, NA, -0.00448947685878404, NA, -0.0446386763157662 ), School3 = c(NA, NA, NA, 0.0261099462365593, NA, 0.0199735626692146, NA, -0.0272279264519992), School4 = c(NA, NA, NA, 0.0164004151291513, NA, 0.00567638888888868, NA, -0.0384017249374949)), .Names = c("schools", "School1", "School2", "School3", "School4"), row.names = c(NA, -8L), class = "data.frame") GraphMelt <- melt(testDF) GraphMelt <- GraphMelt %>% mutate(text = sprintf("%1.2f%%", 100*value)) GraphMelt[,"text"] <- ifelse(GraphMelt[,"text"]=="NA%",NA,GraphMelt[,"text"]) p <- ggplot(GraphMelt, aes(variable, schools)) p <- p + geom_tile(aes(fill = value*100), colour = "white") + geom_text(aes(label=text),size=7) p <- p + scale_fill_gradient(low = "red", high = "green",limits=c(-8,8)) p <- p + theme( axis.text.x= element_text(color="black", size=14, vjust=0.5), axis.text.y= element_text(color="black", size=14, vjust=0.5), axis.title.y = element_text(color="black",size=14, vjust=0.5), plot.title = element_text(color="black",size=14,face="bold", hjust=0.5,vjust=1), panel.background = element_blank(), legend.position="right", legend.title = element_blank(), legend.key = element_rect(fill="white"), legend.background = element_rect(fill=NA) ) p <- p + xlab("") + ylab("") + ggtitle("Schools") 
+5
source share
1 answer

Download the weight package (you already have it, but I want to be explicit regarding this dependency)

 library(scales) 

and add labels = percent to your fill scale

 scale_fill_gradient(low = "red", high = "green",limits=c(-8,8), labels = percent) 
+11
source

Source: https://habr.com/ru/post/1215922/


All Articles