tjebo
tjebo

Reputation: 23817

Not to draw specific part of polygon

I have the following data structure:

y <- rep(1:10, 2)
group <- rep(c('a', 'b'), each = 10)
dens <- c(c(seq(from = 0, to = 0.8, by = 0.1), 0),
           c(seq(from = -0, to = -0.8, by = -0.1), 0))
my_dat <- data.frame(group, dens, y, stringsAsFactors = FALSE )

These are calculated density disributions, in order to make a grouped violin plot, such as in
Split violin plot with ggplot2

# Plot 1:
  require(ggplot2)
  ggplot(my_dat, aes(x = dens, y = y, fill = group)) +
  geom_polygon(color = 'black', show.legend = FALSE)

Now this is simplified, because my data contains hundreds of rows for a smooth outline. (However, there is the central vertical line in my case.) I would now like to remove exactly this vertical central line.
(I guess the problem is removing any specified part of the polygon.)

An idea in my example was to overplot this with a vertical line:

#Plot 2
  ggplot(my_dat, aes(x = dens, y = y, fill = group)) +
  geom_polygon(color = 'black', show.legend = FALSE) +
  geom_segment(x = 0, 
               xend = 0, 
               y = min(y) + 0.2, 
               yend = max(y) - 0.2, 
               color = '#00BFC4')

enter image description here

But to get the end of the over plotting segment line correct is tricky. (I have purposefully left the line a bit too short for demonstration)

edit

the groups are not distributed in a symmetrical fashion, although my example strongly suggests so.

Upvotes: 1

Views: 61

Answers (2)

Claus Wilke
Claus Wilke

Reputation: 17820

I think the simpler solution is to first draw all the outlines and then all the filled areas. This should work for any arbitrary polygon shapes.

y <- rep(1:10, 2)
group <- rep(c('a', 'b'), each = 10)
dens <- c(c(seq(from = 0, to = 0.8, by = 0.1), 0),
         c(seq(from = -0, to = -0.8, by = -0.1), 0))
my_dat <- data.frame(group, dens, y, stringsAsFactors = FALSE )

require(ggplot2)
ggplot(my_dat, aes(x = dens, y = y)) +
  geom_polygon(color = 'black', fill = NA, size = 2) +
  geom_polygon(aes(fill = group), color = NA)

enter image description here

Upvotes: 1

rawr
rawr

Reputation: 20811

You can always just plot another polygon on top

x <- with(my_dat, chull(dens, y))
my_dat2 <- my_dat[c(x, x[1L]), ]

ggplot(my_dat, aes(x = dens, y = y, fill = group)) +
  geom_polygon(show.legend = FALSE) +
  geom_polygon(data = my_dat2, aes(group = 1), size = 1,
               fill = 'transparent',
               # fill = NA,  ## or this
               color = 'black')

enter image description here

Upvotes: 2

Related Questions