ggplot:基于用户定义颜色的组的颜色点 [英] ggplot: colour points by groups based on user defined colours
问题描述
我试图定义在ggplot中绘制的点组的颜色。我改编自此帖子的代码:
但是一旦我有相同的分组变量定义了多行而不是每行的单独的颜色),代码失败,我不知道为什么。下面是一个可重现的例子:
#create一些数据
zone< - c(E,E (50,100,150,200,250,300,350)#x变量
D <-c(c),(c),c,c,c,c, .4,.45,.20,.22,.30,.31,.35)#y variable
df1
#create基于分组变量'zone'的配色方案
zone< -c(E,C)
color.codes&字符(c(#3399FF,#FF0000))
color.names <-c(blue,red)
df2 = data.frame(zone,color.codes, color.names); df2
#合并颜色规格与数据
df <-merge(df1,df2,by =(zone),all.x = TRUE,all.y = TRUE); df
数据类似如下:
zone D col color.codes color.names
C 0.20 150#FF0000 red
C 0.22 200#FF0000 red
C 0.30 250#FF0000 red
E 0.40 50#3399FF blue
E 0.45 100#3399FF blue
E 0.31 300#3399FF blue
E 0.35 350#3399FF blue
目标是生成一个绘图,其中区域'C'中的点为红色,而'E'中的点为蓝色,示例引用一切以红色绘制:
p < - ggplot(data = df,aes(col,D,color =区域))+
geom_point()
p + scale_colour_manual(breaks = df $ zone,values = df $ color.codes)
任何人都可以看到致命的缺陷,为什么这个代码不会在这种方式在组间工作?
提前感谢这么多
如果您使用 unique
和 as.character
:
ggplot(data = df,aes(col,D,color = zone))+
pre>
geom_point()+
scale_colour_manual(breaks = df $ zone,
values = unique(as.character(df $ color.codes)))
>
I am trying to define the colours of groups of points plotted in ggplot. I adapted code from this post:
Color ggplot points based on defined color codes
but as soon as I have more than one row defined by the same grouping variable (rather than a separate colour for each row), the code fails, and I can't figure out why. Below is a reproducible example:
#create some data zone <- c("E","E","C","C","C","E","E") #grouping variable col <- c(50,100,150,200,250,300,350) #x variable D <- c(.4,.45,.20,.22,.30,.31,.35) #y variable df1 <- data.frame(zone, D, col); df1 #create a colour scheme based on grouping variable 'zone' zone <-c("E","C") color.codes<-as.character(c("#3399FF", "#FF0000")) color.names<-c("blue", "red") df2=data.frame(zone, color.codes, color.names); df2 # merge color specifications with data df <-merge(df1,df2, by=("zone"), all.x=TRUE, all.y=TRUE); df
The data then look like this:
zone D col color.codes color.names C 0.20 150 #FF0000 red C 0.22 200 #FF0000 red C 0.30 250 #FF0000 red E 0.40 50 #3399FF blue E 0.45 100 #3399FF blue E 0.31 300 #3399FF blue E 0.35 350 #3399FF blue
The goal is to produce a plot where points in zone 'C' are red and those in 'E' are blue, but using the code from the example cited everything is plotted in red:
p <- ggplot(data=df, aes(col, D, colour = zone))+ geom_point() p + scale_colour_manual(breaks = df$zone, values = df$color.codes)
Can anyone see the fatal flaw, why this code won't work across groups in this way?
Thanks so much in advance解决方案It works if you use
unique
andas.character
:ggplot(data = df, aes(col, D, colour = zone))+ geom_point() + scale_colour_manual(breaks = df$zone, values = unique(as.character(df$color.codes)))
这篇关于ggplot:基于用户定义颜色的组的颜色点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!