legend in 2 columns in r

To add a legend with two columns in ggplot2, you can use the guide_legend function along with the nrow argument. Here's an example code:

main.r
library(ggplot2)

# Create a simple plot
p <- ggplot(mtcars, aes(x = mpg, y = disp, color = factor(cyl))) +
  geom_point()

# Modify the legend
p <- p + guides(color = guide_legend(nrow = 2))

# Show the plot
p
211 chars
12 lines

In this example, nrow = 2 specifies that the legend should be split into two columns. You can adjust this argument to split the legend into more or fewer columns as needed.

related categories

gistlibby LogSnag