如何在ggplot2中设置固定的连续颜色值 [英] How to set fixed continuous colour values in ggplot2

查看:1936
本文介绍了如何在ggplot2中设置固定的连续颜色值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制大量图形,我希望它们都具有相同的色阶,以便我可以相互比较。这里是我的代码:

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

有没有办法设置这个色阶?

解决方案

我能正确理解这个吗?您有两张图,其中色标的值在不同的地块上被映射到不同的颜色,因为地块中没有相同的值。

<$ p $ ($ g $ g $ g $ g $ g $ g $ g $ g $ g $ g $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' color = carb))+
geom_point(size = 6)

  ggplot (子集(mtcars,am == 1),aes(x = wt,y = mpg,color = carb))+ 
geom_point(size = 6)
pre>



在最上面的一个,深蓝色是1,浅蓝色是4,而在深蓝色是深蓝色(仍然)1,但浅蓝色现在是8。



您可以通过给该比例提供 limits 参数来修复颜色条的末端;它应该覆盖数据在任何地块可以采取的整个范围。此外,您可以将这个比例分配给一个变量,并将其添加到所有图中(以减少冗余代码,以便定义只在一个地方,而不是在每个图中)。

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

ggplot(子集(mtcars,am == 0),aes(x = wt,y = mpg,color = carb))+
geom_point size = 6)+ sc


$ g $ p $ ggplot(subset(mtcars,am == 1))/ gzF3U.pngalt =在这里输入图片描述>

,aes(x = wt,y = mpg,color = carb))+
geom_point(size = 6)+ sc


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?

解决方案

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)

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

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

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

这篇关于如何在ggplot2中设置固定的连续颜色值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆