Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove border from geom_rect using ggplot2

Tags:

r

ggplot2

I have this code:

library(ggplot2)
ggplot(data = bayes, aes(x = Order, y = value, fill=key, color=key)) +
  geom_rect(aes(xmin = Order, xmax = dplyr::lead(Order), ymin= -Inf, ymax =Inf, colour=Summary), 
            alpha=0.1) +
  geom_line(size=0.5) + 
  geom_point() + 
  xlab("Bayesian combination") +
  ylab("Bayesian probability") +
  theme(legend.position="none") +
  ylim(0,1) + 
  xlim(1,126)

Just for you to know my data structure:

> str(bayes)
'data.frame':   252 obs. of  5 variables:
 $ Summary    : chr  "1 vs. 6" "1 vs. 6" "1 vs. 6" "1 vs. 6" ...
 $ Combination: chr  "I1 if I2CP3P4M1M2" "I2 if I1CP3P4M1M2" "C if I1I2P3P4M1M2" "P3 if I1I2CP4M1M2" ...
 $ Order      : int  126 125 124 123 122 121 120 119 118 117 ...
 $ key        : chr  "Lower_XVIII_UBU" "Lower_XVIII_UBU" "Lower_XVIII_UBU" "Lower_XVIII_UBU" ...
 $ value      : num  1 0.35 0.93 0.73 0.95 0.32 0.88 0.13 0.93 0.84 ...

My problem is that I cannot remove the outlines and borders from the geom_rect objects, making the figure unintelligible.

enter image description here

As you can see, I have 5 groups represented by five colors. However, within them there are plenty subrectangles each with their own border. I would like to remove all borders in the chart, so, where is the problem in the code?

like image 425
antecessor Avatar asked May 15 '18 06:05

antecessor


1 Answers

Example from the docs:

df <- data.frame(
    x = rep(c(2, 5, 7, 9, 12), 2),
    y = rep(c(1, 2), each = 5),
    z = factor(rep(1:5, each = 2)),
    w = rep(diff(c(0, 4, 6, 8, 10, 14)), 2)
)

You are doing this:

ggplot(df, aes(xmin = x - w / 2, xmax = x + w / 2, ymin = y, ymax = y + 1, fill = z)) +
    geom_rect(aes(color = z), alpha = 0.1)

enter image description here

The problem is that the alpha is only applied to the fill, and not to the border (set with color). The solution is to remove the border entirely by setting (not mapping) color to NA:

ggplot(df, aes(xmin = x - w / 2, xmax = x + w / 2, ymin = y, ymax = y + 1, fill = z)) +
    geom_rect(color = NA, alpha = 0.3)

enter image description here

like image 190
Axeman Avatar answered Oct 28 '22 12:10

Axeman