是否可以根据geom_text中粘贴的不同列指定颜色

时间:2016-12-29 07:08:50

标签: r ggplot2

我有一个ggplot,我有geom_text来粘贴图上的列值。我实际上在我的情节上粘贴了多个列。是否可以根据颜色区分列?

df <- data.frame(YearMonth = c(200606,200606,200608,200701,200703,200605),
             person1 = c('Alice','Bob','Alice','Alice','Bob','Alice'),
             person2 = c('Bob','Alice','Bob','Bob','Alice','Bob'),
             Event = c('event1','event2','event3','event3','event2','event4')
             )

df$YM <- as.Date(paste0("01",df$YearMonth), format="%d%Y%m")
rangeYM <- range(df$YM)
ypts <- rep_len(c(-1,1), length.out=nrow(df))

以下是我用于绘图的代码。

ggplot()+geom_blank(aes(x= rangeYM, y = c(-1,1))) + labs(x = "", y = "") +
theme(axis.ticks = element_blank()) +
geom_hline(yintercept = 0, col = 'maroon') +
geom_segment(aes(x = df$YM, y = 0, xend = df$YM, yend = ypts), arrow = arrow(length = unit(0.2,"cm"))) +
scale_x_date(date_labels = '%b-%y', date_breaks = "month", minor_breaks = NULL) +
scale_y_continuous(minor_breaks = NULL) +
geom_text(aes(x = df$YM, y = 0, label = paste(format(df$YM, "%b-%y")), vjust = 1.5), colour = "#5B7FA3", size = 3, fontface = "bold") +
geom_text(aes(x = df$YM, y = ypts, label = paste(df$person1,df$person2,df$Event,sep="\n")))

从数据框person1可以看出,person2Event是列,并以相同的颜色表示。我尝试通过在colour的{​​{1}} aes中添加geom_text来指定不同的颜色,如下所示。

geom_text(aes(x = df$YM, y = c(-1,1), label = paste(df$person1,df$person2,df$Event,sep="\n"), colour = factor(df$person1,df$person2,df$Event)))

但这给了我一个错误。如果我在因子colour = factor(df$Person1)中包含一列,则它会为Person1列的值指定不同的颜色。但是我希望根据列来区分颜色,因为我在图中粘贴了多个列。

如果有选项,请提供帮助。

1 个答案:

答案 0 :(得分:2)

我想在这种情况下,最简单的方法是使用单独的geoms。

另外,我强烈建议您将data.frames传递给data参数,而不是使用全局环境中的对象或$中的aes表示法。根据我的经验,这往往会让你在某种程度上咬住后面,这是不好的做法。

ggplot()+geom_blank(aes(x= rangeYM, y = c(-1,1))) + labs(x = "", y = "") +
  theme(axis.ticks = element_blank()) +
  geom_hline(yintercept = 0, col = 'maroon') +
  geom_segment(aes(x = df$YM, y = 0, xend = df$YM, yend = ypts), arrow = arrow(length = unit(0.2,"cm"))) +
  scale_x_date(date_labels = '%b-%y', date_breaks = "month", minor_breaks = NULL) +
  scale_y_continuous(minor_breaks = NULL) +
  geom_text(aes(x = df$YM, y = 0, label = paste(format(df$YM, "%b-%y")), vjust = 1.5), colour = "#5B7FA3", size = 3, fontface = "bold") +
  geom_text(aes(x = YM, y = ypts, label = person1), df, col = 'red', nudge_y = .1) +
  geom_text(aes(x = YM, y = ypts, label = person2), df, col = 'darkgreen') +
  geom_text(aes(x = YM, y = ypts, label = Event), df, col = 'blue', nudge_y = -.1)

enter image description here