With the following code I generate some data and then print "R" with a solid line and "W" with a dashed line.
For organizational and aesthetic reasons I would like to separate the legend titles into two groups: Condition for "H C" and "I C" and Model for "R" and "W". In the legend, in the case of Condition we would represent the colors, and in the case of Model the type of line (discontinuous or non-discontinuous) using a standard black.
When using pipes, the problem is not so trivial it seems.
library(dplyr)
library(ggplot2)
library(scales)
tribble( ~y, ~cb, ~z, ~x,
1 , 0, "H C R" ,1,
2 , 1, "H C R" ,1,
2 , 0, "I C R" ,1,
3 , 1, "I C R" ,1,
1.5 , 0, "H C W" ,1,
2 , 1, "H C W" ,1,
2 , 0, "I C W" ,1,
2 , 1, "I C W" ,1,
3 , 0, "H C R" ,2,
3 , 1, "H C R" ,2,
0.5 , 0, "I C R" ,2,
2 , 1, "I C R" ,2,
2 , 0, "H C W" ,2,
2 , 1, "H C W" ,2,
1 , 0, "I C W" ,2,
1 , 1, "I C W" ,2)-> datos
aux<-datos %>%
group_by(x, z, cb) %>%
summarise(media = mean(y),
desvio = rnorm(1),#Tube que simular la desvio sd() arrojaba NaN
error_est = desvio / sqrt(n()),
intervalo_sup = media + (2*error_est),
intervalo_inf = media - (2*error_est)) #%>%
library(RColorBrewer)
display.brewer.pal(11,name = "Spectral")
brewer.pal(n = 11, name = "Spectral")
# Que la línea de condición "H C" apareciera en el color anaranjado que utiliza la paleta "Spectral".
# Que la línea de condición "I C" apareciera en el color verde oscuro que utiliza la paleta "Spectral".
colores<-brewer.pal(n = 11, name = "Spectral")[c(3,3,9,9)]
ggplot() +
geom_line(data=aux%>%filter(grepl("W",z)),
aes(x = x, y = media, color = z,group = z),
size=0.5,
linetype = "dashed") +
geom_errorbar(data=aux%>%filter(grepl("W",z)),aes(x = x, color = z,
ymax = intervalo_sup,
ymin = intervalo_inf),
width=0.3) +
geom_line(data=aux%>%filter(!grepl("W",z)),
aes(x = x, y = media, color = z,group = z),
size=0.5) +
geom_errorbar(data=aux%>%filter(!grepl("W",z)),
aes(x = x, color = z,
ymax = intervalo_sup,
ymin = intervalo_inf),
width=0.3)+
labs(x = "x", y = "y", color = "Condition") +
scale_color_manual(values=colores) +
scale_x_continuous(breaks = seq(1,7, by=1)) +
theme(legend.position="bottom", legend.text=element_text(size=12)) +
guides(color=guide_legend(ncol=2)) +
theme(axis.text=element_text(size=14),
axis.title=element_text(size=14))+
facet_wrap(~cb)
The following code generates a better approximation of what you expect (this time using pipes)