Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend for summary statistics in ggplot2

Tags:

r

ggplot2

Here is the code for the plot

library(ggplot2)
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)), y = rnorm(30))
library(plyr)
ds <- ddply(df, .(gp), summarise, mean = mean(y), sd = sd(y))
ggplot(df, aes(x = gp, y = y)) +
   geom_point() +
   geom_point(data = ds, aes(y = mean), colour = 'red', size = 3)

enter image description here

I want to have a legend for this plot that will identify the data values and mean values some thing like this

Black point = Data
Red point   = Mean.

How can I achieve this?

like image 409
MYaseen208 Avatar asked Aug 07 '12 04:08

MYaseen208


People also ask

How do I add a legend in ggplot2?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

How do I find summary statistics in R?

R provides a wide range of functions for obtaining summary statistics. One method of obtaining descriptive statistics is to use the sapply( ) function with a specified summary statistic. Possible functions used in sapply include mean, sd, var, min, max, median, range, and quantile.

Which plot gives statistical summary?

A histogram and a combined dot-, box-, mean-, percentile- and SD- plot give a visual summary and statistics such as the mean, standard deviation skewness, kurtosis and median, percentiles summarise the sample numerically.

What does Geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot.


1 Answers

Use a manual scale, i.e. in your case scale_colour_manual. Then map the colours to values in the scale using the aes() function of each geom:

ggplot(df, aes(x = gp, y = y)) +
  geom_point(aes(colour="data")) +
  geom_point(data = ds, aes(y = mean, colour = "mean"), size = 3) +
  scale_colour_manual("Legend", values=c("mean"="red", "data"="black"))

enter image description here

like image 194
Andrie Avatar answered Oct 16 '22 09:10

Andrie