Reputation: 164
I am looking for a way, to have two or more segments in the legend as well as the Median of a Boxplot. I have come up with the following example:
y = data.frame(runif(500))
library(ggplot2)
ggplot(data = y )+
aes(0, y)+
geom_boxplot(outlier.shape = 1)+
scale_y_continuous(name = "",limits = c(0,1))+
scale_x_discrete(name = "")+
geom_segment( aes(x=-0.362, y=0.6, xend=0.363,yend=0.6, linetype = "R
fans"), linetype = "dashed", colour = "black")+
geom_segment( aes(x=-0.35, y=0.8, xend=0.35,yend=0.8, linetype =
"frustated R users"), col = "red" )+
theme_bw()+
theme(legend.title = element_blank())+
theme(legend.background = element_rect(fill="white",
size=0.1, linetype="solid",
colour ="black"))
The geom_segment with y=0.6 shall be in the legend with a dashed black line. At the moment I picked linetype twice, which does not make sense, but if I erase the second linetype the colour in the legend turns red or the linetype changes into another not required one. It should be black and dashed for the plot as well as for the legend. For y = 0.8 it works well, as the linetype by default is the right one.
Additionally, I would like to have a third line in the legend. The third line shall be the median line, which is a solid, thick, black line.
Thanks for any help in advance.
Upvotes: 2
Views: 2042
Reputation: 164
I augmented PoGibas very helpful answer to two different linetypes as well:
y = data.frame(runif(500))
dLines <- data.frame(X =c(-0.362, -0.35),
Y = c(0.6, 0.8),
Xend = c(0.363, 0.35),
Yend=c(0.6, 0.8),
Group = c("TypeA", "TypeB"),
color = c("black", "red"),
linetype = c( "solid", "dashed"))
ggplot(data = y )+
aes(0, y)+
geom_boxplot(outlier.shape = 1)+
scale_y_continuous(name = "",limits = c(0,1))+
scale_x_discrete(name = "")+
geom_segment(data = dLines,
aes(x = X, xend = Xend,
y = Y, yend = Yend,
color = Group,
linetype = Group))+
scale_color_manual(values = dLines$color) +
scale_linetype_manual(values = dLines$linetype) +
theme_bw()+
theme(legend.title = element_blank())+
theme(legend.background = element_rect(fill="white",
size=0.1, linetype="solid",
colour ="black"))
Upvotes: 1
Reputation: 28369
Solution by passing lines as seperate data.frame
, setting individual line colour by color = Group
and specifying those colours with scale_color_manual
.
library(ggplot2)
# Generate data
dBox <- data.frame(y = rnorm(10))
dLines <- data.frame(X =c(-0.362, -0.35),
Y = c(0.6, 0.8),
Xend = c(0.363, 0.35),
Yend=c(0.6, 0.8),
Group = c("typeA", "typeB"),
color = c("black", "red"))
ggplot(dBox, aes(0, y)) +
geom_boxplot(outlier.shape = 1)+
scale_y_continuous(name = "",limits = c(0,1))+
scale_x_discrete(name = "") +
geom_segment(data = dLines,
aes(x = X, xend = Xend,
y = Y, yend = Yend,
color = Group)) +
scale_color_manual(values = dLines$color) +
theme_bw() +
theme(legend.title = element_blank()) +
theme(legend.background = element_rect(fill = "white",
size = 0.1,
linetype = "solid",
colour = "black"))
Upvotes: 3