I have a ggplot and I have geom_text
to paste column values on the plot. I actually pasted multiple columns on my plot. Is it possible to differentiate the columns based on colour?
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))
Below is the code I have used for plotting.
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")))
As it can be seen from the dataframe person1
, person2
,Event
are columns and are represented in same colour. I tried to assign different colour by including colour
in aes
of geom_text
as below.
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)))
But this gives me an error. If I include one column in factor i.e colour = factor(df$Person1)
then it assigns different colours to values of Person1 column. But I want the colour to be differentiated based on columns as I am pasting multiple columns in the plot.
Please help if there is an option to do so.