thiagoveloso
thiagoveloso

Reputation: 2763

Adding geom_text from different data frame to facets

I am plotting monthly precipitation totals for multiple years at a certain location using ggplot2:

library(ggplot2)
df.mon <- data.frame(id=rep("Station 1", 192),
                     month=rep(seq(1:12), 16),
                     year=rep(1999:2014, each=12),
                     monprec=runif(n=192, min=0, max=400))

ggplot(df.mon, aes(x=month, y=monprec)) +
  geom_bar(stat="identity") +
  theme_bw(base_size=18) +
  facet_wrap(~year, ncol=3)

enter image description here

On the same figure, I want to add annotations with the annual precipitation totals, which are in a second data frame:

df.year <- data.frame(id=rep("Station 1", 16),
                      year=1999:2014,
                      totprec=runif(n=16, min=200, max=1000))

My first approach would be to use geom_text(), but the df.year data frame doesn't have a month column that can be used as the y argument in aes().

Any ideas to help me achieve my goal?

Upvotes: 2

Views: 1015

Answers (1)

Dan
Dan

Reputation: 12084

I might've missed the point, but how about this?

# Data frames
df.mon <- data.frame(id=rep("Station 1", 192),
                     month=rep(seq(1:12), 16),
                     year=rep(1999:2014, each=12),
                     monprec=runif(n=192, min=0, max=400))

df.year <- data.frame(id=rep("Station 1", 16),
                      year=1999:2014,
                      totprec=runif(n=16, min=200, max=1000))

# Plotting
library(ggplot2)

ggplot(df.mon, aes(x=month, y=monprec)) +
  geom_bar(stat="identity") +
  theme_bw(base_size=18) +
  facet_wrap(~year, ncol=3) +
  ylim(c(0, 500)) +
  geom_text(data = df.year, aes(x = 6.25, y = 450, label = round(totprec)))

enter image description here

Here, I just specify the x and y coordinates for the annual precipitation annotation in the aes for the geom_text.

Upvotes: 3

Related Questions