coloured plot of tapply() with ggplot2

Viewed 89

I would like to plot (scatterplot) the result of tapply(a$weight, a$row_variant, mean) in R

 5.1         5.2         5.3         6.1         6.2         6.3         7.1         7.2 
0.001845968 0.001582964 0.001701220 0.001505864 0.001505433 0.001604114 0.001545241 0.001546341 
        7.3 
0.001734087 

The row-variant should be on the x-axis, the weight on the y-axis. Each point of the same variant (e.g. 5.1, 6.1 and 7.1) should have the same colour. So far I solved this with plot(), but didn´t managed the coloring there.

xnames <- names(tapply(a$weight,a$row_variant,mean))
 plot(tapply(a$weight,a$row_variant,mean),xaxt="n", main="Median", xlab="row.variant", ylab="Median", ylim=c(0, 0.011))
 axis(1, at=1:length(xnames), labels=xnames)
1 Answers

Convert the output of tapply into a dataframe using stack, then plot using ggplot:

d <- stack(tapply(mtcars$mpg, mtcars$cyl, mean))
d
#     values ind
# 1 26.66364   4
# 2 19.74286   6
# 3 15.10000   8

library(ggplot2)

ggplot(d, aes(values, ind)) + 
  geom_point()

enter image description here

Related