Forcing specific plot symbols for points in R ggplot2

175 views Asked by At

I am trying to specify manually, the shape of data points in r ggplot2 but can't seem to get it to work. Below is a sample example

p.est<- c(1.65, 1.55, 0.70, 1.61, 1.25)
lcl<-c(1.25, 1.10, 0.50, 1.20, 1.02)
ucl<-c(2.20, 2.05, 0.90, 2.20, 1.50)
toy.data <- tibble(zc = zc, p.est = p.est, p.lcl = p.lcl, p.ucl = p.ucl)

Assume I want two types of plot symbols for the five points, I use scale_shape_manual() in ggplot2 but it doesn't seem to work. Below is my sample code and the resulting plot attached. I'm trying to modify so the plot symbols for the points correspond to 5 which is a diamond and 16 which is a circle.

ggplot(toy.data, aes(zc,  p.est, ymin = p.lcl, ymax = p.ucl)) + 
  scale_shape_manual(values = c(5, 16, 5, 5, 16))+
  geom_pointrange(position = position_dodge(width = 0.1))+
  geom_hline(yintercept = 1)+
  ylim(0.5, 2.5)

enter image description here

1

There are 1 answers

7
guasi On BEST ANSWER

You can add shape = factor(p.est). Otherwise scale_shape doesn't apply to anything.

zc    <- c(1,2,3,4,5)
p.est <- c(1.65, 1.55, 0.70, 1.61, 1.25)
p.lcl   <-c(1.25, 1.10, 0.50, 1.20, 1.02)
p.ucl   <-c(2.20, 2.05, 0.90, 2.20, 1.50)

toy.data <- tibble(zc = zc, 
                   p.est = p.est, 
                   p.lcl = p.lcl, 
                   p.ucl = p.ucl)

ggplot(toy.data, aes(zc,  p.est, ymin = p.lcl, ymax = p.ucl, shape = factor(p.est))) + 
  scale_shape_manual(values = c(5, 16, 5, 5, 16)) +
  geom_pointrange(position = position_dodge(width = 0.1)) +
  geom_hline(yintercept = 1) +
  ylim(0.5, 2.5)

EDITED Follow up question

toy.data <- tibble(zc = zc, 
                   p.est = p.est, 
                   p.est.x = c("A","B","A","A","B"),
                   p.lcl = p.lcl, 
                   p.ucl = p.ucl)

ggplot(toy.data, aes(zc,  p.est, ymin = p.lcl, ymax = p.ucl, shape = p.est.x)) + 
  scale_shape_manual(values = c(5, 16)) +
  geom_pointrange(position = position_dodge(width = 0.1)) +
  geom_hline(yintercept = 1) +
  ylim(0.5, 2.5)