0

I prepare to draw a schematic plot rather than data visulization.So the importing data is not data.frame. Most of lines add by manual operation (ie. geom_segment, geom_vline). I found it hard to display the linetype legend or color legend. Maybe it do not accord with ggplot ideology, but it is convenient way to adding singular line without combining to data.frame.

x <- 1:10
y <- 2:11
plt <- ggplot()+
  geom_point(aes(x=x,y=y),shape=1,color='red',show.legend=TRUE)+
  geom_line(aes(x=x,y=y),linetype=2,color='green')+
  geom_segment(aes(x=Inf,y=y[3],xend=x[3],yend=y[3]),color='blue',linetype=5)+
  geom_vline(xintercept=x[4],linetype=6,size=2)+
  scale_linetype_manual(values=c(2,5,6),labels=c('a','b','c'))

enter image description here

Dave2e
  • 22,192
  • 18
  • 42
  • 50
Cobin
  • 888
  • 13
  • 25
  • What is the reason as to why you prefer not to have a `data.frame`? – NelsonGon Dec 22 '18 at 08:03
  • 1
    @NelsonGon because I want to add some `geom_vline` and `geom_hline`, which is not easy to combine with data in a data.frame. – Cobin Dec 22 '18 at 08:06

1 Answers1

1

Is this what you are after:

library(ggplot2)
x <- 1:10
y <- 2:11
ggplot()+
  geom_point(aes(x=x,y=y, color='red'),shape=1,show.legend=FALSE) +
  geom_line(aes(x=x,y=y, linetype= "Line A"), color='green') +
  geom_segment(aes(x=Inf,y=y[3],xend=x[3],yend=y[3], 
                   linetype = "Line B"), color='blue')+
  geom_segment(aes(x = 4, y= Inf, xend = 4, yend = -Inf, 
                   linetype = "Line C"), size = 2) +
  scale_linetype_manual(name = "Legend", values = c(2,5,6), 
                        guide = guide_legend(override.aes = 
                                        list(color = c("green", "blue", "black"),
                                        size = c(.5, .5, 2))))

Creates:

enter image description here

Using answer <How to add a legend to hline?>

I can't see a way of adding the red points to the legend without adding points to all the legend lines. So not a complete answer.

A not very elegant work around may be:

ggplot()+
  geom_point(aes(x=x,y=y, linetype='APoints'), 
             colour = "Red", size = 2, shape=18) +
  geom_line(aes(x=x,y=y, linetype= "Line A"), color='green') +
  geom_segment(aes(x=Inf,y=y[3],xend=x[3],yend=y[3], 
                   linetype = "Line B"), color='blue') +
  geom_segment(aes(x = 4, y= Inf, xend = 4, yend = -Inf, 
                   linetype = "Line C"), size = 2) +
  scale_linetype_manual(name = "Legend", values = c(2,5,6,2), 
                    guide = guide_legend(override.aes = 
                                  list(color = c("red", "green", "blue", "black"),
                                       size = c(1, .5, .5, 2),
                                       linetype = c("dotted", "dashed", 
                                                    "dashed", "dotdash"))))

to get this:

enter image description here

Pete
  • 600
  • 1
  • 6
  • 16