在添加特定于构面的注释时,构面按字母顺序排序

时间:2018-02-22 14:18:32

标签: r ggplot2 facet

我制作了一个有多个方面的情节,并希望像这样指定方面顺序:

library(tidyverse)

df <- tribble(
  ~year, ~country, ~value,
  2001, "France", 55, 
  2002, "France", 53, 
  2003, "France", 31, 
  2004, "France", 10, 
  2005, "France", 30, 
  2006, "France", 37, 
  2007, "France", 54, 
  2008, "France", 58, 
  2009, "France", 50, 
  2010, "France", 40, 
  2011, "France", 49, 
  2001, "USA", 55,
  2002, "USA", 53,
  2003, "USA", 64,
  2004, "USA", 40,
  2005, "USA", 30,
  2006, "USA", 39,
  2007, "USA", 55,
  2008, "USA", 53,
  2009, "USA", 71,
  2010, "USA", 44,
  2011, "USA", 40
) %>% 
  mutate(country = factor(country, c("USA", "France")))

ggplot(df, aes(year, value)) +
  geom_line() +
  facet_wrap(~country)

哪个情节: enter image description here

因此USAFrance覆盖默认字母顺序之前显示为一个方面。

然后我想在这些方面添加一些文字并使用不同的颜色:

annot <- tribble(
  ~country, ~year, ~value, ~label,
  "France", 2004, 50, "Baguette",
  "USA", 2005, 50, "Hamburgers")

ggplot(df, aes(year, value)) +
  geom_line() +
  facet_wrap(~country) +
  geom_text(aes(label = label, x = year, y = value), 
            data = annot %>% filter(country == "France"),
            color = "red")  +
  geom_text(aes(label = label, x = year, y = value), 
            data = annot %>% filter(country == "USA"),
            color = "blue")

哪个情节:

enter image description here

但现在再次France之前绘制了USA!所以我正在寻找一种方法来保持我指定的原始方面顺序。

1 个答案:

答案 0 :(得分:1)

正如@Axeman所说。这(基本上重复上面的代码)按预期工作:

annot <- tribble(
  ~country, ~year, ~value, ~label,
  "France", 2004, 50, "Baguette",
  "USA", 2005, 50, "Hamburgers") %>%
  mutate(country = factor(country, c("USA", "France")))