简体   繁体   中英

How to append lines in a plot with ggplot2

I am trying to make a plot like this in an easy way with ggplot (or base R)

在此处输入图像描述

The idea is to consider the dark line as a single group with a gap between two subgroups (CAP and NC), and also to put a second x lab to tag times (as you can see, times 0,15 and 240 are common to both groups).

Thanks for your help,

EDIT: Here there is an example.

db0 <- structure(list(t = c(0, 5, 15, 30, 60, 0, 15, 60, 0, 5, 15, 
30,60, 0, 15, 60), g = c("C", "C", "C", "C", "C", "N", "N", "N", 
"C", "C", "C", "C", "C", "N", "N", "N"), v = c("T1", "T1", "T1", 
"T1", "T1", "T1", "T1", "T1", "T2", "T2", "T2", "T2", "T2", "T2", 
"T2", "T2"), y = c(10, 12, 15, 25, 33, 10, 13, 11, 11, 20, 28, 
14, 10, 11, 11, 12), x = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 
2L, 3L, 4L, 5L, 6L, 7L, 8L)), row.names = c(NA, -16L), class = 
"data.frame")

db0$x <- rep(1:8, length.out=16)

library(ggplot2)
ggplot(db0, aes(x=as.factor(x), y=y, group=g, color=v)) + 
  geom_path() + 
  geom_point() +
  scale_x_discrete(labels=c("1" = "0",  "2" = "5", "3" = "15", "4" = "30",
                            "5" = "60", "6" = "0", "7" = "15", "8" = "60"))

在此处输入图像描述

The question here is how to do this plot in an easy way, without creating the x variable and the changing the x-lab names, but with ggplot2 commands. Also, Having problems with geom_path that links the end of one group with the beginning of the following.

  1. Use group = interaction(g, v) to prevent the lines from connecting.
  2. I think you can use facet_grid to get similar results.

BTW, I'm using x=t here to get the actual value for the x-axis instead of attempting to map it with ordinals and such.

ggplot(db0, aes(x=t, y=y, group=interaction(g, v), color=v)) + 
  geom_path() + 
  geom_point() +
  facet_grid(. ~ g, space = "free_x")

多面 ggplot2 与线断开

I added space="free_x" here to attempt to get the x-axis on the right to compress, which is when I noticed that the x-range is the same for the left and the right... theoretically, if they were different, the size of each pane might be proportional. (See https://stackoverflow.com/a/10455381/3358272 )

There is a bit of formatting/labeling you'll need to do to get the "CAP" and "NC" labels you seek.

If you need similar x-ranges but dissimilar widths, then you will likely need to munge the x-axis of one of the groups and then attach a labeller somehow that distinguishes between the two groups.

A third option is to produce two separate plots (using different x-axis controls) and use a package like patchwork to combine them with dissimilar widths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM