Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

r - How to set fixed continuous colour values in ggplot2

I'm plotting a lot of graphics and I'd like for all of them to have the same colour scale so I can compare one to another. Here's my code:

myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))
print(ggplot(mydata, aes(x= X, y= Y, colour= Z)) + geom_point(alpha=.5,size = 6) + scale_colour_gradientn(colours = myPalette(100)) + ylim(.1,.4) + xlim(1.5,2) + ggtitle(title))

Is there a way to set this colour scale?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do I understand this correctly? You have two plots, where the values of the color scale are being mapped to different colors on different plots because the plots don't have the same values in them.

library("ggplot2")
library("RColorBrewer")
ggplot(subset(mtcars, am==0), aes(x=wt, y=mpg, colour=carb)) + 
  geom_point(size=6)

enter image description here

ggplot(subset(mtcars, am==1), aes(x=wt, y=mpg, colour=carb)) + 
  geom_point(size=6)

enter image description here

In the top one, dark blue is 1 and light blue is 4, while in the bottom one, dark blue is (still) 1, but light blue is now 8.

You can fix the ends of the color bar by giving a limits argument to the scale; it should cover the whole range that the data can take in any of the plots. Also, you can assign this scale to a variable and add that to all the plots (to reduce redundant code so that the definition is only in one place and not in every plot).

myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))
sc <- scale_colour_gradientn(colours = myPalette(100), limits=c(1, 8))

ggplot(subset(mtcars, am==0), aes(x=wt, y=mpg, colour=carb)) + 
  geom_point(size=6) + sc

enter image description here

ggplot(subset(mtcars, am==1), aes(x=wt, y=mpg, colour=carb)) + 
  geom_point(size=6) + sc

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...