Replacing ggplot2 legend key for geom_line with symbol

后端 未结 2 388
暗喜
暗喜 2021-01-07 10:30

I have a line plot of prices for three stocks, which I normalise by taking the percentage change from the beginning of the period I am looking at. This seems to work fine, b

相关标签:
2条回答
  • 2021-01-07 11:19

    In ggplot the legend matches the plot itself. So, to get circles or squares in the legend you need to add circles or squares to the plot.

    This can be done with geom_point(shape=...). shape=1 generates circles, shape=7 generates squares.

    chart1 + geom_point(shape=7)
    

    enter image description here

    0 讨论(0)
  • 2021-01-07 11:31

    You can define new geom like this:

    GeomLine2 <- proto(GeomLine, {
        objname <- "line2"
        guide_geom <- function(.) "polygon"
        default_aes <- function(.) aes(colour = "black", size=0.5, linetype=1, alpha = 1, fill = "grey20")
         })
    geom_line2 <- GeomLine2$build_accessor()
    
    chart1 <- ggplot(data=changes,aes(x=Date, y=value, colour=variable, fill = variable))
    chart1 <- chart1 + geom_line2(lwd=0.5) + ylab("Change in price (%)") + xlab("Date") +
      labs(colour="Company",  fill = "Company")
    print(chart1)
    

    Not sure but note that this will not work in the next version of ggplot2.

    enter image description here

    0 讨论(0)
提交回复
热议问题