Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. data(iris)
  2. library(ggplot2)
  3. g <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour=Species), alpha=0.5) #desired plot
  4.  
  5. plot(iris$Sepal.Length, iris$Petal.Length, col=iris$Species) #attempt in base graphics
  6.  
  7. g2 <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour=Species, alpha=Petal.Width))
  8.  
  9. getColWithAlpha <- function(colLevel, alphaLevel)
  10. {
  11. maxAlpha <- max(alphaLevel)
  12. cols <- rainbow(length(levels(colLevel)))
  13. res <- cols[colLevel]
  14. sapply(seq(along.with=res), function(i) adjustcolor(res[i], alphaLevel[i]/maxAlpha) )
  15. }
  16.  
  17. plot(iris$Sepal.Length, iris$Petal.Length,
  18. col = getColWithAlpha(iris$Species, iris$Petal.Width), pch = 20)
  19.  
  20. COL <- adjustcolor(c("red", "blue", "darkgreen")[iris$Species], alpha.f = 0.5)
  21. plot(iris$Sepal.Length, iris$Petal.Length, col = COL, pch = 19, cex = 1.5) #attempt in base graphics
  22.  
  23. # Allocate Petal.Length to 7 length categories
  24. seq.pl <- seq(min(iris$Petal.Length)-0.1,max(iris$Petal.Length)+0.1, length.out = 7)
  25.  
  26. # Define number of alpha groups needed to fill these
  27. cats <- nlevels(cut(iris$Petal.Length, breaks = seq.pl))
  28.  
  29. # Create alpha mapping
  30. alpha.mapping <- as.numeric(as.character(cut(iris$Petal.Length, breaks = seq.pl, labels = seq(100,255,len = cats))))
  31.  
  32. # Allocate species by colors
  33. COLS <- as.data.frame(col2rgb(c("red", "blue", "darkgreen")[iris$Species]))
  34.  
  35. # Combine colors and alpha mapping
  36. COL <- unlist(lapply(1:ncol(COLS), function(i) {
  37. rgb(red = COLS[1,i], green = COLS[2,i], blue = COLS[3,i], alpha = alpha.mapping[i], maxColorValue = 255)
  38. }))
  39.  
  40. # Plot
  41. plot(iris$Sepal.Length, iris$Petal.Length, col = COL, pch = 19, cex = 1.5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement