为ggplot2中的条分配颜色

时间:2018-07-24 09:27:36

标签: r ggplot2 colors

如何在以下代码中为各个任务分配不同的颜色?我希望他们都不同。

task1 <- c('Ass: Data Vis', '2018-07-24', '2018-07-29')
task2 <- c('Ass: Elevator Pitch', '2018-07-25', '2018-08-05')
task3 <- c('Ass: Short Essay', '2018-07-25', '2018-08-12')
task4 <- c('Ass: Abstract', '2018-08-05', '2018-08-19')
df <- as.data.frame(rbind(task1, task2, task3, task4))
names(df) <- c('task', 'start', 'end')
df$task <- factor(df$task, levels = df$task)
df$start <- as.Date(df$start)
df$end <- as.Date(df$end)
df_gath <- gather(df, "date", "value", 2:3)
start_date <- as.Date('2018-07-15')

ggplot(df_gath, aes(value, task)) + 
  geom_line(size = 8, colour = "orange") +
  labs(x = '', y = '', title = 'Planner', size = 12) +
  theme_bw(base_size = 8) +
  theme(plot.title = element_text(hjust = 0.5),
    panel.grid.major.x = element_line(colour="black", linetype = "dashed"),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.text.x = element_text(angle = 0)) +
  scale_x_date(date_labels = "%Y %b", limits = c(start_date, NA), date_breaks = '1 month')

1 个答案:

答案 0 :(得分:1)

只需定义,颜色=任务即可。

  ggplot(df_gath, aes(value, task, color = task)) + 
  geom_line(size = 8) +
  labs(x = '', y = '', title = 'Planner', size = 12) +
  theme_bw(base_size = 8) +
  theme(plot.title = element_text(hjust = 0.5),
        panel.grid.major.x = element_line(colour="black", linetype = "dashed"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.text.x = element_text(angle = 0)) +
  scale_x_date(date_labels = "%Y %b", limits = c(start_date, NA), date_breaks = '1 month')+
  scale_color_manual(values = c("blue", "blue", "green", "green"))