Reputation:
In ggplot2, how could I change the color of coloring in scatter plot?
Upvotes: 10
Views: 26490
Reputation: 43440
Here's a small dataset:
dat <- data.frame(x=1:20,
y=rnorm(20,0,10),
v=20:1)
Suppose I want my points colored using the value v. I can change the way in which the coloring is performed using the scale_colour_gradient() function.
library(ggplot2)
qplot(x,y,data=dat,colour=color,size=4) +
scale_colour_gradient(low="black", high="white")
This example should just get you started. For more, check out the scale_brewer()
mentioned in the other post.
Upvotes: 12
Reputation: 7109
If your data have discrete categories that you wish to colour, then your task is a bit easier. For example, if your data look like this, with each row representing a transaction,
> d <- data.frame(customer = sample(letters[1:5], size = 20, replace = TRUE),
> sales = rnorm(20, 8000, 2000),
> profit = rnorm(20, 40, 15))
> head(d,6)
customer sales profit
a 8414.617 15.33714
a 8759.878 61.54778
e 8737.289 56.85504
d 9516.348 24.60046
c 8693.642 67.23576
e 7291.325 26.12234
and you want to make a scatter plot of transactions coloured by customer, then you can do this
p <- ggplot(d, aes(sales,profit))
p + geom_point(aes(colour = customer))
to get....
Upvotes: 8
Reputation: 17348
check out the ggplot documentation for scale_brewer http://www.had.co.nz/ggplot2/scale_brewer.html
some examples:
#see available pallets:
library(RColorBrewer)
display.brewer.all(5)
#scatter plot
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
d <- qplot(carat, price, data=dsamp, colour=clarity)
dev.new()
d
dev.new()
d + scale_colour_brewer(palette="Set1")
dev.new()
d + scale_colour_brewer(palette="Blues")
Upvotes: 9