Nicolabo
Nicolabo

Reputation: 1377

add additional legend in boxplot abbreviations

I have a problem with adding legend with explanation of abbreviations. Fo example

df <- data.frame(value = c(seq(1,50,1),seq(21,70,1),seq(41,90,1)),
             name = c(rep("A-B",50),rep("B-C",50),rep("A-C",50)))

ggplot(df, aes(name, value))+
geom_boxplot()

enter image description here

I have data.frame with explanation of abbreviations.

full_name <- data.frame(abb =c("A","B","C"),fname = c("Ananas","Banana","Cucumber"))

I want to add legend with info what each letter means.

Upvotes: 1

Views: 1404

Answers (3)

jburkhardt
jburkhardt

Reputation: 675

#add fill=name generates legend
ggplot(df, aes(name, value, fill=name)) +
  geom_boxplot() +
#customize legend
scale_fill_discrete(name="Legend\nTitle",
                                breaks=c("A-B", "B-C", "A-C"),
                                labels=c("Ananas-Banana", "Banana-Cucumber", "Ananas-Cucumber"))

enter image description here

Upvotes: 1

Ruthger Righart
Ruthger Righart

Reputation: 4921

The following code makes an additional vector "Legend" and displays it as legend.

df <- data.frame(value = c(seq(1,50,1),seq(21,70,1),seq(41,90,1)),
             name = c(rep("A-B",50),rep("B-C",50),rep("A-C",50)))

Legend <- as.character(df$name)
Legend <- replace(Legend, Legend=="A-B", "A-B = Ananas-Banana")
Legend <- replace(Legend, Legend=="A-C", "A-C = Ananas-Cucumber")
Legend <- replace(Legend, Legend=="B-C", "B-C = Banana-Cucumber")

library(ggplot2)
ggplot(df, aes(x = name, y = value, colour = Legend))+
geom_boxplot()

enter image description here

Upvotes: 1

Roland
Roland

Reputation: 132706

library(ggplot2)
p <- ggplot(df, aes(name, value))+
  geom_boxplot()

library(gridExtra)
grid.arrange(p, tableGrob(full_name, rows = NULL), nrow = 1, widths = c(4, 1))

resulting plot

Upvotes: 6

Related Questions