Change the label of legend not by changing…

Change the label of legend not by changing the data.

# data
grp <- gl(n=4,k=20,labels=c("group a","group b","group c", "group d"))
value <- runif(n=80, min=10, max=150)
outcome <- cut(value,2)
data <- data.frame(grp,value,outcome)

# Option 1
# breaks should be exactly the same as the levels of the factor
ggplot(data, aes(grp, fill=outcome)) + geom_bar() +xlab("group") +
    ylab("number of subjects") + 
    scale_fill_discrete("Serologic response", 
                        breaks=c("(12.1,79.7]","(79.7,147]"),   # should be the same as the levels of the factor
                        labels=c("double negative", "positive for a and/or b")
                        )

# Option 2
# simpler because factor() takes care of the levels of the factor
ggplot(data, aes(grp, 
         fill=factor(outcome,labels=c("double negative","positive for a")))) + 
    geom_bar() +xlab("group") +ylab("number of subjects") +
    labs(fill="Serologic response")

http://stackoverflow.com/questions/7323191/how-do-i-manually-change-the-key-labels-in-a-legend-in-ggplot2

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *