Ploting melted variable using facet_wrap

2019-08-31 07:03发布

问题:

I would like to create a plot with 6 facets.

I am using a melted dataset.

When using :

ggplot(g,aes(x = x, y = value, colour = variable, linetype = variable,size = variable)) + 
    geom_line() + facet_wrap(.~condition)

I get the error:

Error in layout_base(data, vars, drop = drop) : 
  At least one layer must contain all variables used for facetting

I don't understand what this means given that I have the variable used for faceting in the variable "condition"

Here is the original data from which the melted variable was created.

This is the code I'm using to produce the plot:

ggplot(g,aes(x = x, y = as.numeric(value), colour = varible, linetype = variable,size = variable)) + 
    geom_line() + 
    scale_x_continuous(breaks=seq(1,10,1)) +
    scale_y_continuous(breaks=seq(0,1, 0.1))+
    scale_colour_manual(values=c("red3","red3","red3","red3", "red3","red3","red3", "red3","red3",   
    "blue3","blue3","blue3","blue3","blue3","blue3","blue3","blue3","blue3")) + 
    scale_linetype_manual(values = c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2)) + 
    scale_size_manual(values = c(0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4)) + 
    xlab("\nTime-steps") + 
    ylab("Proportion correct\n") +
    theme_bw() +
    theme(axis.text=element_text(size=5),
          axis.title=element_text(size=5),
          axis.line = element_line(size=0.25),
          axis.ticks=element_line(size=0.25),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.border = element_blank(),
          panel.background = element_blank(),
          legend.position="none" ,
          legend.direction="vertical", 
          legend.title=element_blank(),
          legend.text=element_text(size=6), 
          legend.background=element_blank(), 
          legend.key=element_blank())+facet_wrap(~condition)

回答1:

You have two main problems - y is coded as a factor and should be numeric, and more importantly there is a tiny typo in your facet_wrap term, which should be without .:

p <- ggplot(g,aes(x = as.numeric(x), y = as.numeric(value), group = variable)) 
p <- p + geom_line()
p <- p + facet_wrap(~condition)
p

This gives me

EDIT: I noted that variable has a size coding embedded. This works nicely to include it in the graphs:

g$size<-substring(g$variable,1,5)

Then add colour = size in the aesthetics and you obtain:



标签: r ggplot2