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
831 views
in Technique[技术] by (71.8m points)

r - Specifying same limits for colorbar (legend) in ggplot2

I want multiple plots to share the same color-scale. A given value in one plot should have the same color as in the second plot. How do I enforce this with ggplot2?

Here is an example of two plots that do not share color-scales, but should:

x <- matrix(1:16, 4)
y <- matrix(1:16-5, 4)
library(reshape)
ggplot(data = melt(x)) + geom_tile(aes(x=X1,y=X2,fill = value))
ggplot(data = melt(y)) + geom_tile(aes(x=X1,y=X2,fill = value))

image image

These two plots look the same, but they should look different!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to set the limits of your scale bar to have certain colors and also define the mean value (the value in the middle) to be a same value for both plots.

rng = range(c((x), (y))) #a range to have the same min and max for both plots



ggplot(data = melt(x)) + geom_tile(aes(x=X1,y=X2,fill = value)) +
  scale_fill_gradient2(low="blue", mid="cyan", high="purple", #colors in the scale
                 midpoint=mean(rng),    #same midpoint for plots (mean of the range)
                 breaks=seq(-100,100,4), #breaks in the scale bar
                 limits=c(floor(rng[1]), ceiling(rng[2]))) #same limits for plots

ggplot(data = melt(y)) + geom_tile(aes(x=X1,y=X2,fill = value)) +
  scale_fill_gradient2(low="blue", mid="cyan", high="purple", 
                 midpoint=mean(rng),    
                 breaks=seq(-100,100,4),
                 limits=c(floor(rng[1]), ceiling(rng[2])))

This is the output:

image image


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

...