在boxplot缩写中添加其他图例

时间:2014-12-15 09:40:17

标签: r ggplot2 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)))

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

enter image description here

我有data.frame,并附有缩写说明。

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

我想添加带有每个字母含义信息的图例。

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

#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

答案 2 :(得分:1)

以下代码会生成一个额外的向量&#34;图例&#34;并将其显示为图例。

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