0
data = data.frame("ID1" = c(1,2,3,1,2,3),
                  "ID2"=c(1,1,1,2,2,2),
                  "D" = sample(5:25,6,r=T))
data$DL = data$D-.02*data$D
data$DU = data$D+.02*data$D
data$XVAL = c(1:6)
library(ggplot2)
ggplot(data) +
  geom_pointrange(aes(ymin=DL,ymax=DU),y=D,x=XVAL,
  colour=as.factor(data$ID1),shape=as.factor(data$ID1),linetype=as.factor(data$ID2))

I wish to generate what is simple: a geom_pointrange figure where colour defined by ID1 and linetype defined by ID2.

I especially am looking to create such a legend as this: enter image description here

ajpat
  • 21
  • 1
  • 8
  • You end `aes()` to early. Delete the `)` after `ymax=DU)` and move it to the very end, `linetype = factor(ID2)))`, so that all your aesthetic mappings are inside `aes()`, and your legend will be created automatically. – Gregor Thomas May 06 '20 at 16:07
  • Also, don't use `data$` inside `aes()`. You can change to `colour = factor(ID1), linetype = factor(ID2)`. – Gregor Thomas May 06 '20 at 16:08
  • @Gregor Thomas thank you so much it is working!! do you have any advice on the legend? – ajpat May 06 '20 at 16:12
  • Glad it's working now. What additional advice are you looking for on the legend? – Gregor Thomas May 06 '20 at 16:14
  • @GregorThomas Thank you so much, if you click the link it will show. I wish to combine shape and color into one legend key and for line type just show linetype without the point in it – ajpat May 06 '20 at 16:19

1 Answers1

0

If you map colour and shape the same way, they should be automatically combined. To get rid of the point on the linetype legend, you can see this question for reference. Putting everything together, try this:

ggplot(data) +
  geom_pointrange(aes(
    ymin = DL,
    ymax = DU,
    y = D,
    x = XVAL,
    colour = factor(ID1),
    shape = factor(ID1),
    linetype = factor(ID2)
  )) +
  labs(color = "", shape = "", linetype = "") +
  guides(
    linetype = guide_legend(override.aes = list(shape = NA)),
    color = guide_legend(override.aes = list(linetype = 0))
  )
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • this is an exact solution thank you. I am lastly just wondering is it possible to sort the bars from highest on D to lowest, instead of by name? It is not part of the question but sort of I'm just wondering – ajpat May 06 '20 at 16:42
  • Yeah, see the FAQ on [ordering bars in ggplot2](https://stackoverflow.com/q/5208679/903061). – Gregor Thomas May 06 '20 at 16:43
  • Oh Jeez, I forgot to ask is it possible to remove the vertical line on the points/shapes from the legend? – ajpat May 06 '20 at 16:44
  • Edited that inn. – Gregor Thomas May 06 '20 at 16:51
  • if you might have insight, https://stackoverflow.com/questions/61383620/r-ggplot-spacing-and-sorting-the-figure – ajpat May 06 '20 at 17:09