以下是我正在尝试解决的问题的可重现示例。我已经在ggplot2中创建了各种各样的热图,事情进展顺利。由于我在geom_text上使用了数据的百分号,我想让geom_tile的图例也显示百分号(我现在只能将实际值乘以100)。理想情况下,我希望右侧的图例栏显示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")
答案 0 :(得分:14)
加载scale包(你已经拥有它,但我希望明确这个依赖)
library(scales)
并将labels = percent
添加到您的填充比例
scale_fill_gradient(low = "red", high = "green",limits=c(-8,8), labels = percent)