"再启动" ggplot中的颜色范围

时间:2015-06-08 00:20:38

标签: r ggplot2

在我的散点图中,我想根据"类型"使用两种不同形状的点。列和填充颜色范围取决于"探测"专栏,但我不希望颜色范围是连续的,我希望它为每个"类型"重新启动。另外,我想让它反映在传奇中。 这就是我现在所拥有的:

require(data.table); require(ggplot2);

mydat <- fread(
"N,type,probe,value
1,A,Abc,2
1,A,Ade,4
1,B,Bfg,3
2,A,Ade,4
2,B,Bhi,3
3,B,Bfg,3
3,A,Axy,2
4,A,Ade,5
5,B,Bfg,2
5,A,Ade,1
6,A,Abc,1
6,B,Bhi,4
  ")

ggplot(mydat,
       aes(x=N, y=value, fill=probe, shape=type, label=probe)) +
  geom_point(size=4, alpha=0.8) +
  scale_shape_manual(values=c(21,22)) +
  scale_fill_discrete(name='probe') +
  geom_text(vjust=-0.8) +
  guides(fill=guide_legend(override.aes=list(shape=24))) 

sample plot

这就是我想要的: desired view

(在这个例子中,&#34; Abc&#34;与&#34; Bfg&#34等颜色相同;但实际上我并不关心颜色的确切对应,我只需要每个新&#34;类型&#34;)

重新开始的比例

1 个答案:

答案 0 :(得分:0)

这是变量映射的非标准用法,因此您可能需要重新考虑绘图的设计(我在这里使用@Chase)。但如果这真的是你想要的,那么你必须手动预先计算调色板,就像这样。我假设type变量的字母顺序,如果情况并非如此,您需要额外的排序。

library(scales)
pal <- numeric(0)
for (tp in unique(mydat$type))
{
  n <- length(unique(subset(mydat, type == tp)$probe))
  pal <- c(pal, hue_pal()(n))
}

ggplot(mydat,
       aes(x=N, y=value, fill=probe, shape=type, label=probe)) +
  geom_point(size=4, alpha=0.8) +
  scale_shape_manual(values=c(21, 22)) +
  scale_fill_manual(name='probe', values = pal) +
  geom_text(vjust=-0.8) +
  guides(fill=guide_legend(override.aes=list(shape=24)))

enter image description here

编辑:对于一致的颜色,请使用例如以下调整

pal <- numeric(0)
max_pal <- 5
for (tp in unique(mydat$type))
{
  n <- length(unique(subset(mydat, type == tp)$probe))
  pal <- c(pal, hue_pal()(max_pal)[1:n])
}

enter image description here