Reputation: 73
I've tried a few methods to change the legend title, but it ends up creating a new legend with that title just below the current legend.
Here is the code:
C1 <- rnorm(200,14,4)
C2 <- rnorm(20,13,2)
C1.date <- sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 200)
C2.date <- sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 20)
dataset <- data.frame(c(C1,C2),c(C1.date,C2.date),c(rep("C1",200),rep("C2",20)))
names(dataset) <- c("A","B","C")
library(ggplot2)
ggplot(data = dataset, aes(x = B, y = A))+
enter code here`xlab("B")+
ylab("A")+
geom_point(aes(color = factor(C)))+
scale_x_date(date_labels = "%b %Y")+
stat_smooth(aes(color = factor(C),fill = factor(C)),method="loess")
Upvotes: 1
Views: 270
Reputation: 39613
Another option would be using guides()
which is similar to the fast solution of @stefan:
library(ggplot2)
#Code
ggplot(data = dataset, aes(x = B, y = A))+
xlab("B")+
ylab("A")+
geom_point(aes(color = factor(C)))+
scale_x_date(date_labels = "%b %Y")+
stat_smooth(aes(color = factor(C),fill = factor(C)),method="loess")+
guides(color=guide_legend(title='MY NEW TITLE'),
fill=guide_legend(title='MY NEW TITLE'))
Output:
Upvotes: 1
Reputation: 125797
Using labs
you have the change both the title for fill
and the color
legend. If you change only one they no longer get merged.
C1 <- rnorm(200,14,4)
C2 <- rnorm(20,13,2)
C1.date <- sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 200)
C2.date <- sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 20)
dataset <- data.frame(c(C1,C2),c(C1.date,C2.date),c(rep("C1",200),rep("C2",20)))
names(dataset) <- c("A","B","C")
library(ggplot2)
ggplot(data = dataset, aes(x = B, y = A))+
xlab("B")+
ylab("A")+
geom_point(aes(color = factor(C)))+
scale_x_date(date_labels = "%b %Y")+
stat_smooth(aes(color = factor(C),fill = factor(C)),method="loess") +
labs(color = "Legend", fill = "Legend")
#> `geom_smooth()` using formula 'y ~ x'
Upvotes: 3