The ggplot legend shows levels that are not in the data

I have a plot, the legend of which should contain two levels. Ggplot shows a legend with six levels, including four that are not displayed in the data frame. The following is a simple reproduction of a problem:

x <- seq(from=1, to=10, by=0.5)
y.2 <- x^2
y.3 <- x^3
exponent.2 <- 2
exponent.3 <- 3
data2 <- data.frame(x=x, y=y.2, exponent = exponent.2)
data3 <- data.frame(x=x, y=y.3, exponent = exponent.3)
data <- rbind(data2, data3)
p <- ggplot(data,aes(x,y,group=exponent, color=exponent)) + geom_line()
p

I'm obviously doing something wrong, but I need help finding a problem.

+3
source share
2 answers

ggplot2 interprets the exponent as a continuous variable; thus, it displays a series of breaks, similar to what was returned pretty(c(2, 3)).

You can use colour = factor(exponent)or explicitly specify color gaps.

+5
source

Try

p <- ggplot(data,aes(x,y,group=factor(exponent), color=factor(exponent))) + geom_line()
+3
source

All Articles