Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change both legend titles in a ggplot with two legends

Tags:

r

legend

ggplot2

I have two legends on my ggplot with two different legend titles (automatically created from ggplot()). Now, I want to change this legend titles. + labs(colour = "legend name") only change the second legend title. How can I change the first one, too?

Sample data:

dataset <- structure(list(date = structure(c(1264572000, 1266202800, 1277362800),  class = c("POSIXt", "POSIXct"), tzone = ""),  x1 = c(-0.00183760994446658, 0.00089738603087497, 0.000423513598318936),  x2 = c("approach x","approach y","approach z"),  x3 = c("Type1", "Type1", "Type2")) , .Names = c("date", "data","code","type"), row.names = c("1", "2", "3"), class = "data.frame") 

Here is my code to produce the plot:

p <- ggplot(dataset, aes(x=date, y=data)) + geom_point(aes(shape = factor(type), color = code)) + scale_shape_manual(value=c(23,15)) print(p) 

The legend titles are on default: "factor(type)" and "code": enter image description here

like image 280
Atticus Avatar asked Aug 02 '11 11:08

Atticus


People also ask

How do I change the legend text in Ggplot 2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I change the title of a legend in R?

guides() can be used to alter legend title. To change the title with this function pass the required name to as an argument to guide_legend() function and this ultimately as the value to the attribute col. Example: R.

How do I reorder my legend ggplot2?

You can use the following syntax to change the order of the items in a ggplot2 legend: scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...)

How do I change the color of my legend in R?

To change the color legend element border using ggplot2, we can use theme function where can put color in legend. key argument to desired color with element_rect.


2 Answers

Here is an example using the iris dataset:

data(iris) ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +     geom_point(aes(shape=Species, colour=Petal.Width)) +      scale_colour_gradient() +     labs(shape="Species label", colour="Petal width label") 

You specify the labels using labs(), with each scale separately specified, i.e. labs(shape="Species label", colour="Petal width label").

enter image description here

like image 84
Andrie Avatar answered Oct 11 '22 12:10

Andrie


If I understood your point correctly, you can simply use + labs(shape = "shape legend title", colour = "colour legend title")

like image 43
Jean-Robert Avatar answered Oct 11 '22 11:10

Jean-Robert