add legend in r

To add a legend to a plot in R using ggplot2, you can use the scale_color_manual or scale_fill_manual functions. Here is an example code block that demonstrates how to use these functions to add a legend to a scatter plot:

main.r
# load ggplot2 library
library(ggplot2)

# create sample data
x <- c(1, 2, 3, 4, 5)
y <- c(1, 4, 9, 16, 25)
df <- data.frame(x, y)

# create scatter plot
ggplot(df, aes(x = x, y = y, color = "Points")) +
  geom_point() +
  scale_color_manual(values = "blue", name = "Legend Title")
282 chars
13 lines

In this example, the color aesthetic is set to the string "Points", which will be used as the label for the legend. The scale_color_manual function is then used to set the color of the points to blue and to set the legend title as "Legend Title".

You can also use scale_fill_manual if you are using fill colors rather than point colors.

gistlibby LogSnag