2017-05-03 254 views
2

我有这样如何改变颜色geom_point或线ggplot

data<- structure(list(sample = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", 
"B"), class = "factor"), y = c(0.99999652, 0.99626012, 0.94070452, 
0.37332406, 0.57810894, 0.37673758, 0.22784684, 0.35358141, 0.21253558, 
0.17715703, 0.99999652, 0.86403956, 0.64054516, 0.18448824, 0.40362691, 
0.10791682, 0.06985696, 0.07384465, 0.0433271, 0.02875159), time = c(100L, 
150L, 170L, 180L, 190L, 220L, 260L, 270L, 300L, 375L, 100L, 150L, 
170L, 180L, 190L, 220L, 260L, 270L, 300L, 375L), x = c(0.9999965, 
0.9981008, 0.9940164, 1.0842966, 0.9412978, 1.0627907, 0.9135079, 
1.1982235, 0.9194105, 0.9361713, 0.9999965, 1.0494051, 0.9526752, 
1.1594711, 0.9827104, 1.0223711, 1.1419197, 1.0328598, 0.6015229, 
0.3745817)), .Names = c("sample", "y", "time", "x"), class = "data.frame", row.names = c(NA, 
-20L)) 

数据我感兴趣的一个打扮的颜色像绘制它的黑色和红色

我可以绘制它两个随机不同的颜色这样的,但问题是,

ggplot() + 
geom_point(data = data, aes(x = time, y = y, color = sample),size=4) 
如果我要指派的第一个(A)为黑色,(B),以红色

。我怎样才能做到这一点?

回答

4

你可以使用scale_color_manual

ggplot() + 
    geom_point(data = data, aes(x = time, y = y, color = sample),size=4) + 
    scale_color_manual(values = c("A" = "black", "B" = "red")) 

enter image description here


每OP的评论,让同色线的点,你可以这样做:

ggplot(data = data, aes(x = time, y = y, color = sample)) + 
    geom_point(size=4) + 
    geom_line(aes(group = sample)) + 
    scale_color_manual(values = c("A" = "black", "B" = "red")) 

enter image description here

+0

如果我想让geom_line过,我应该只有一次scale_color_manual使用?例如一条红线和一条黑线 – nik

+0

是的,你会做'scale_color_manual'一次,然后你的'geom_line'看起来像这样:'geom_line(aes(x = time,y = y,group = sample,颜色=样品))' –

+0

感谢迈克这是一个很好的解决方案 – nik

0

我会做这样的(你也可以用十六进制的颜色,而不是红色,黑色)

data <- data %>% 
    mutate(Color = ifelse(sample == "A", "black", 
       ifelse(sample == "B", "red", "none"))) 

ggplot() + 
    geom_point(data = data, aes(x = time, y = y, color = Color),size=4)+ 
    scale_color_identity() 
+0

这是非常多_not_建议使用ggplot的方式。 – bdemarest

+0

纠正我,如果我错了,但我相信这里不需要“填充”审美。 –

+0

Bdemarest我不确定这个大问题是什么。如果你要批评你,至少可以解释为什么。在我看来,如果我使用数据框来制作一堆不同的图形,它可以让我从大量的输入/指定颜色中解脱出来。 – Knachman