14

样本数据集:

library(ggplot2)    
df = read.table(text = 
              "id      year    value1  value2 value3
            1           2000    1   2000      2001
            1           2001    2   NA        NA
            1           2002    2   2000      NA
            1           2003    2   NA         2003
            2           2000    1   2001     2003
            2           2002    2   NA       2000
            2           2003    3   2002     NA
            3           2002    2   2001     NA
        ", sep = "", header = TRUE)
df$value1 <- as.factor(df$value1)

我知道如何更改具有三个级别的因子变量的颜色:

p <- ggplot(df, aes(y=id))
p <- p + scale_colour_manual(name="",  values =c("yellow", "orange", "red"))
p <- p + geom_point(aes(x=year, color=value1), size=4)
p

我还可以更改两个数值变量的颜色:

p <- ggplot(df, aes(y=id))
p <- p + scale_colour_manual(name="",  values =c("value3"="grey", "value2"="black"))
p <- p + geom_point(aes(x=value3, colour ='value3'), size=3)
p <- p + geom_point(aes(x=value2, colour ='value2'), size=5)
p

但我不知道如何在同一张图中更改两者的颜色?它也适用于 scale_color_manual 吗?

p <- last_plot() + geom_point(aes(x=year, color=value1))
p
4

2 回答 2

27

这是你想要的?

ggplot(df, aes(y=id)) +
  geom_point(aes(x=year, color=value1), size=4) +
  geom_point(aes(x=value3, colour ='value3'), size=3) +
  geom_point(aes(x=value2, colour ='value2'), size=5) +
  scale_colour_manual(name="",  
                      values = c("1"="yellow", "2"="orange", "3"="red",
                                 "value3"="grey", "value2"="black"))

在此处输入图像描述

基本上,只需将所有可能的颜色标签放在一个列表中。

于 2013-11-08T20:05:06.010 回答
2

JLLagrange 的想法是正确的。在绘图之前使用meltfromreshape2将数据转换为长格式。

df_long <- melt(df,id.vars = c("id", "year"), measure.vars=c("value2", "value3"))
(p <- ggplot(df_long, aes(y = id)) + 
  scale_colour_manual(name = "", values = c(value3 = "grey", value2 = "black")) +
  scale_size_manual(name = "", values = c(value3 = 3, value2 = 5)) +
  geom_point(aes(x = value, colour = variable, size = variable))
)

根据您的评论,您的数据应该采用不同的形式。本质上,您正在考虑value2value3与 相同year,但为 增加了额外的级别value1。像这样重建您的数据:

df1 <- df[, c("id", "year", "value1")]

df2 <- data.frame(
  id     = df$id,
  year   = df$value2,
  value1 = "4"
)

df3 <- data.frame(
  id     = df$id,
  year   = df$value3,
  value1 = "5"
)

df_all <- rbind(df1, df2, df3)
df_all$value1 <- factor(df_all$value1)

然后你可以用这个画一个图:

(p <- ggplot(df_all, aes(id, year, colour = value1)) + 
  geom_point(
    size = 3, 
    position = position_jitter(height = 0, width = 0.05)
  ) +
  scale_colour_manual(
    values = c("1" = "yellow", "2" = "orange", "3" = "red", "4" = "grey", "5" = "black")
  )
)

(我为这些点添加了一些抖动,以便您可以看到它们重叠的位置。您也可以在 中设置一个alphageom_point。)

于 2013-11-05T15:23:33.587 回答