Home > Blockchain >  Adjust yend in geom_segment when x is categorical
Adjust yend in geom_segment when x is categorical

Time:04-29

I would like to adjust the vertical position of the geom_segment when x is categorical. In the example below the geom_segment is centered around the variable on the x-axis.

I would like draw the segment starting on the line of the x-axis variable and extending towards above. I tried something like yend = variable 1 which obvisouly does not work.

The question is somewhat similar to this question regarding geom_vline with categorical axis. However, I think something like yintercept = ... would not work in my case.

library(tidyverse)

mydata = data.frame(variable = factor(c("A","A","A","B","C")),
                    color = factor(c(1,2,3,4,5)),
                    start = c(1,2,1,4,6),
                    end = c(3,4,6,5,8))

ggplot(mydata, aes(x = start, xend = end, y = variable, yend = variable))   
  geom_segment(aes(color = color), size = 10)

Created on 2022-04-28 by the reprex package (v2.0.1)

The reason I ask is because in my real data I add a histogram to each x-variable (with ggridges::geom_density_ridges) which starts on the line of the x-axis variable. The plot looks strange if geom_segment and geom_density_ridges do not lie on the same level.

CodePudding user response:

Maybe you can use geom_rect instead.

library(ggplot2)
mydata = data.frame(variable = factor(c("A","A","A","B","C")),
                    color = factor(c(1,2,3,4,5)),
                    start = c(1,2,1,4,6),
                    end = c(3,4,6,5,8))

ggplot(mydata)   
  geom_rect(aes(xmin = start, xmax = end, 
                ymin = variable, ymax = as.numeric(variable)   0.2, 
                fill = color))

Created on 2022-04-28 by the reprex package (v2.0.1)

  • Related