Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alpha in geom_segment not working [duplicate]

I was trying few refinements in my plot and encounter that alpha in geom_segment is not working properly. For minimum working example check this:

ggplot(mtcars, aes(hp, mpg)) + 
  geom_point() + 
  geom_segment(aes(x = 100, xend = 200, y = 20, yend = 20), 
  inherit.aes = FALSE, 
  size = 10, 
  alpha = 0.5, 
  color = "blue")

However, if you change the alpha to really low value such as 0.005, 0.001 appears working. You can only see some effect from 0.05 to 0.001.

Aren't the alpha values supposed to change in a linear manner between 0 and 1 or have I understood incorrectly?

like image 410
TheRimalaya Avatar asked Jan 02 '23 22:01

TheRimalaya


1 Answers

ggplot2 is drawing many segments, one on top of each other making the segment opaque. You can solve it by removing the data from the ggplot function and add it to the required layers. Similar problem with other geoms here and here.

ggplot() + 
    geom_point(data=mtcars, aes(hp, mpg)) + 
    geom_segment(aes(x = 100, xend = 200, y = 20, yend = 20), 
                 inherit.aes = FALSE, 
                 size = 10, 
                 alpha = 0.5, 
                 color = "blue")

enter image description here

Another option is to use annotate as Eric did:

ggplot(mtcars) +
    geom_point(aes(hp, mpg)) +
    annotate(
      'segment',
      x = 100,
      xend = 200,
      y = 20,
      yend = 20,
      size = 10,
      colour = "blue",
      alpha = 0.5
    ) 
like image 146
mpalanco Avatar answered Jan 05 '23 14:01

mpalanco