Control column widths in a ggplot2 graph with a series and inconsistent data

后端 未结 2 933
一向
一向 2020-12-04 00:01

In the artificial data I have created for the MWE below I have tried to demonstrate the essence of a script I have created in R. As can be seen by the graph that gets produ

2条回答
  •  Happy的楠姐
    2020-12-04 01:02

    Yeah, I figured what happened: you need to be extra careful about factors being factors and numerics being numerics. In my case, with stringsAsFactors = FALSE I have

    str(df)
    'data.frame':   7 obs. of  3 variables:
     $ x: chr  "1" "2" "3" "1" ...
     $ s: chr  "No" "No" "No" "Yes" ...
     $ y: chr  "1" "2" "3" "2" ...
    
    dput(df)
    structure(list(x = c("1", "2", "3", "1", "2", "3", "4"), s = c("No", 
    "No", "No", "Yes", "Yes", "Yes", "Yes"), y = c("1", "2", "3", 
    "2", "3", "4", "5")), .Names = c("x", "s", "y"), row.names = c(NA, 
    -7L), class = "data.frame")
    

    with no factors and numeric turned into character because of cbind-ing (sic!). Let us have another data frame:

    dff <- data.frame(x = factor(df$x), s = factor(df$s), y = as.numeric(df$y))
    

    Adding a "dummy" row (manually for your example, check out expand.grid version in the linked question on how to do this automatically):

    dff <- rbind(dff, c(4, "No", NA))
    

    Plotting (I removed extra aes):

    ggplot(data = df3, aes(x, y, fill=s)) + 
      geom_bar(position=dodge_str, stat="identity", size=.3, colour="black")
    

    enter image description here

提交回复
热议问题