仅在一个方面内使用ggplot' s注释

时间:2017-07-20 12:28:33

标签: r ggplot2 facet annotate

我正在做一个复杂的ggplot可视化,我在这里为不同的国家(在方面)绘制了几个时间序列。我想手动为一个方面注释系列,以便更容易快速查看哪个是哪个,而无需查看图例。

这是我的简化示例:

library(tidyverse)

df <- tribble(
  ~year, ~country, ~series1, ~series2, 
  #--|--|--|----
  2003, "USA", 8, 5,
  2004, "USA", 9, 6, 
  2005, "USA", 11, 7, 
  2006, "USA", 10, 8,
  2007, "USA", 11, 4,
  2008, "USA", 14, 10,
  2009, "USA", 16, 12,
  2010, "USA", 12, 8,
  2011, "USA", 12, 13,
  2012, "USA", 13, 10,
  2013, "USA", 11, 5,
  2005, "FRA", 5, 6, 
  2006, "FRA", 6, 8, 
  2007, "FRA", 5, 7, 
  2008, "FRA", 4, 8,
  2009, "FRA", 9, 11,
  2010, "FRA", 7, 9, 
  2011, "FRA", 14, 11,
  2012, "FRA", 7, 11, 
  2013, "FRA", 6, 6,
  2014, "FRA", 5, 7,
  2015, "FRA", 4, 5
)

ggplot(df, aes(x = year)) +
  geom_line(aes(y = series1, color = "First series")) +
  geom_line(aes(y = series2, color = "Second series")) +
  facet_wrap(~country) +
  annotate("text", x = 2014, y = 13, label = "First series") +
  annotate("text", x = 2014, y = 8, label = "Second series")

产生下图:

enter image description here

如何删除左侧面(我手动划掉的)中的注释?

更新:回复@ user20650&#39; hint,我也试过了:

ann_text <- tribble(
  ~year, ~country, ~series1, ~series2,
  #--|--|--|----
  2014, "USA", 13, 8
)

ggplot(df, aes(x = year)) +
  geom_line(aes(y = series1, color = "First series")) +
  geom_line(aes(y = series2, color = "Second series")) +
  facet_wrap(~country) +
  geom_text(data = ann_text, label = "Text")

产生以下错误:

Error: geom_text requires the following missing aesthetics: y

1 个答案:

答案 0 :(得分:1)

最终解决了这个问题:

library(tidyverse)

df <- tribble(
  ~year, ~country, ~series1, ~series2, 
  #--|--|--|----
  2003, "USA", 8, 5,
  2004, "USA", 9, 6, 
  2005, "USA", 11, 7, 
  2006, "USA", 10, 8,
  2007, "USA", 11, 4,
  2008, "USA", 14, 10,
  2009, "USA", 16, 12,
  2010, "USA", 12, 8,
  2011, "USA", 12, 13,
  2012, "USA", 13, 10,
  2013, "USA", 11, 5,
  2005, "FRA", 5, 6, 
  2006, "FRA", 6, 8, 
  2007, "FRA", 5, 7, 
  2008, "FRA", 4, 8,
  2009, "FRA", 9, 11,
  2010, "FRA", 7, 9, 
  2011, "FRA", 14, 11,
  2012, "FRA", 7, 11, 
  2013, "FRA", 6, 6,
  2014, "FRA", 5, 7,
  2015, "FRA", 4, 5
)

ann_text1 <- tribble(
  ~year, ~country, ~series1, ~series2,
  #--|--|--|----
  2014, "USA", 13, 8
)

ann_text2 <- tribble(
  ~year, ~country, ~series1, ~series2,
  #--|--|--|----
  2014, "USA", 8.5, 9
)

ggplot(df, aes(x = year)) +
  geom_line(aes(y = series1, color = "First series")) +
  geom_line(aes(y = series2, color = "Second series")) +
  facet_wrap(~country) +
  geom_text(data = ann_text1, aes(y = series1), label = "First") +
  geom_text(data = ann_text2, aes(y = series1), label = "Second")

这使得:

enter image description here