[R] Problems with facets in ggplot2

Nick Wray n|ckmwr@y @end|ng |rom gm@||@com
Fri Aug 4 12:08:10 CEST 2023


Hello  I am wrestling with ggplot – I have produced a facetted plot of
flows under various metrics but I can’t find info on the net which tells me
how to do three things


I have created some simplified mock data to illustrate (and using a
colour-blind palette):


library(ggplot2)

library(forcats)

cb8<- c("#000000", "#E69F00", "#56B4E9", "#009E73","#F0E442", "#0072B2",
"#D55E00", "#CC79A7")

set.seed<-(040823)

  mock<- set.seed<-(040823)


mock<-as.data.frame(cbind(rep((1990:1995),8),round(rnorm(48,50,10),3),rep(c(rep("Tweed",6),rep("Tay",6)),4),rep(c("AMAX","Mean","AMIN","Median"),each=12)))

  colnames(mock)<-c("Year","Flow","Stat","Metric")

  mock



  ggplot(mock, aes(Year,Flow, group = factor(Stat), colour = factor(Stat)))+

    coord_cartesian(ylim = c(0, 100)) +

    geom_line(size=1)+

    scale_color_manual(name = "Stat", values = cb8[4:7])+

    scale_y_discrete(breaks=c(0,25,50,75,100),labels=c(0,25,50,75,100))+

    facet_wrap(vars(Metric),nrow=2,ncol=2)+

    ylab("Flow")



1)This gives me a facetted plot but I can’t work out why I’m not getting a
labelled y scale



2)Why are plots down at the bottom of the facets rather than in the middle?



3)And also I’d like the plots to be in the order (top left to bottom right)
of

AMAX MEAN AMIN MEDIAN

but if I add in the line
facet_grid(~fct_relevel(Metric,"AMAX","Mean","AMIN","Median")) before the
line ylab it disrupts the 2x2 layout



Can anyone tell me how to resolve these problems?  Thanks Nick Wray

	[[alternative HTML version deleted]]



More information about the R-help mailing list