Search code examples
rggplot2widthgroupingrows

How to separate groups of lanes in ggplot2 geom_point?


I am plotting data from a data.frame which is structured like this:

    A       B       C       D
    29.8    8.7     0.1     Type_1

The first three columns are floats and the last is a string. There are 13 possible strings in column 4, and for each of those strings, a row is generated in the plot via geom_point(). The float values in the first three columns are used to populate the rows of "points" (irrelevant here). Basically, each row contains thousands of points which scatter according to their values in A,B and C.

Here's how it looks like (without axis labels since it is unpublished stuff):

PLOT

Now the question: I would like to group the rows according to different criteria by increasing the width between them in a specific way, that is, not by increasing the width between rows generally but specifically where I want it. How to do so?

An imaginary example: type_1 and type_2 belong together and have to be observed together, while type_3 must be separated to avoid confusion.

Bottom line: is there a quick and easy way to specify the width between groups of rows?

Here is the relevant part of my plot code:

P1 <- ggplot(...) + 
geom_point(position = position_jitter(w = 0.15, h = 0), alpha=0.3, size=0.5) +
scale_x_discrete() +
scale_y_continuous(limits=c(0,100), breaks=seq(0,100,10)) + 
scale_color_gradient2(breaks=seq(0,100,20), 
                      limits=c(0,100), 
                      low="green3",
                      high="darkorchid4",
                      midpoint=50,
                      name="") +
coord_flip()

Solution

  • I believe the easiest way to solve your problem is to create a column "E" in your data frame with a "grouping" factor. Since you have not provided reusable data, I believe Dplyr is the best solution for creating this additional column, but I cannot offer a chunk of code. The output should be something like this:

     A       B       C       D       E
    29.8    8.7     0.1     Type_1  group_1
    29.6    8.2     0.7     Type_2  group_1
    ...
    

    Then you can use facet_wrap(~E, ncol=1) in the following manner:

    P1 <- ggplot(...) + 
    geom_point(position = position_jitter(w = 0.15, h = 0), alpha=0.3, size=0.5) +
    scale_x_discrete() +
    scale_y_continuous(limits=c(0,100), breaks=seq(0,100,10)) + 
    scale_color_gradient2(breaks=seq(0,100,20), 
                      limits=c(0,100), 
                      low="green3",
                      high="darkorchid4",
                      midpoint=50,
                      name="") +
    coord_flip()+
    facet_wrap(~E, ncol=1)