Home > Blockchain >  How to set data factor sorting in ggplot2 plot
How to set data factor sorting in ggplot2 plot

Time:11-27

I now have a set of 4*16 data, and I want to use ggplot2 to draw a nice faceted line chart like Figure 1, but my code is like this,I know through some information that I think there is something wrong with the sorting of my data, but I don't know how to adjust it.please help me.enter image description here

 data<-data.frame(A=c(0.05,0.10,0.05,0.10,0.05,0.10,0.05,0.10,0.05,0.10,0.05,0.10,0.05,0.10,0.05,0.10),
               B=c(1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3),
               C=c(1,1,1,1,5,5,5,5,6,6,6,6,10,10,10,10),
               D=c(1.3221625,1.3006163,1.3091457,1.2738161,1.2470091,
                  1.1765646,1.1838100,1.0545490,1.2307647,1.1513869,
                  1.1569168,1.0097403,1.1758619,1.068641,1.0578440,
                  0.8668918))
 ggplot(data,aes(x=factor(C),y=D, colour=B)) 
 geom_point(shape=1) 
 facet_wrap(~A,ncol = 2, nrow = 2) geom_line()
 

CodePudding user response:

You were nearly there:

# helper function to create facet strip label (see documentation for `ggplot2::as_labeller()` for more details and examples.

appender <- function(string, prefix = "shrinkage:") paste0(prefix, string)

library(ggplot2)
  ggplot(data, aes(x = C, y = D, colour = factor(B))) 
  geom_point() 
  geom_line()  
  facet_wrap(~ A, labeller = as_labeller(appender),  ncol = 2) 
    labs(x = NULL, 
         y = NULL, 
         colour = NULL) 
    theme(legend.position = "top")

Created on 2022-11-27 with reprex v2.0.2

  •  Tags:  
  • r
  • Related