guide_legend and ggplot2, format nrow

2019-09-05 00:46发布

问题:

I am trying to format an over-long legend on a ggplot so that there is a maximum no. of rows. I've read all the documentation that I could find, especially this: http://docs.ggplot2.org/0.9.3.1/guide_legend.html but for some reason, the legend will not format.

I've given a reproducible sample below using the quakes dataset, and converted the column stations to character so that they plot individually (otherwise, they seem to plot as groups).

plotquakes <- function(magreq) {
    library(ggplot2)
    magdata <- subset(quakes, mag > magreq)
    magdata$stations <- as.character(magdata$stations)
    g <- ggplot(magdata, aes (x = lat, y = long))
    g + geom_point(aes(alpha = stations), fill = "black", pch=21, size = 6) + 
    labs(x = "Latitude", y = "Longitude") + 
    geom_vline(xintercept = 0, col = "red") + 
    geom_hline(yintercept = 0, col = "red") +
    guides(col = guide_legend(nrow = 16))
}

plotquakes(5)

And what I get is this:

whereas I would like to have a maximum of 16 data fields per column in the legend.

回答1:

You are changing the wrong guide.

plotquakes <- function(magreq) {
  library(ggplot2)
  magdata <- subset(quakes, mag > magreq)
  magdata$stations <- as.character(magdata$stations)
  g <- ggplot(magdata, aes (x = lat, y = long))
  g + geom_point(aes(alpha = stations), fill = "black", pch=21, size = 6) + 
    labs(x = "Latitude", y = "Longitude") + 
    geom_vline(xintercept = 0, col = "red") + 
    geom_hline(yintercept = 0, col = "red") +
    guides(alpha = guide_legend(nrow = 16)) #note it's alpha not col
}

plotquakes(5)



标签: r ggplot2