在多面图中更改geom_line的颜色

时间:2019-06-16 02:00:57

标签: r ggplot2 facet-grid

我希望每个国家/地区的线条与我手动设置的颜色相同。即。瑞典=红色,美国=蓝色,加拿大=绿色。

如何最好地做到这一点?

library(tidyverse)

df <- tibble(
  date = rep(c(as.Date("1995-01-01"), as.Date("1995-01-01"), as.Date("1996-01-01"), as.Date("1996-01-01")), 3),
  decile = rep(c("d1", "d2"), 6),
  income = c(10, 30, 15, 35, 50, 60, 70, 80, 90, 100, 110, 120),
  country = c(rep("Sweden", 4), rep("Canada", 4), rep("USA", 4))
)

g <- ggplot(df, aes(x = date, y = income)) +
  geom_line(aes(colour = decile), size = 2) +
  scale_color_manual(values = c("red", "green", "blue", "black")) 

g + facet_grid(~ country)

1 个答案:

答案 0 :(得分:2)

编辑:删除了映射区分十分项。

g <- ggplot(df, aes(x = date, y = income, group = decile, color = country)) +
  geom_line(size = 2) +
  scale_color_manual(values = c("Sweden" = "red", "Canada" = "green", 
                                "USA" = "blue")) + 
  facet_grid(~ country)
g

enter image description here