Matt
Matt

Reputation: 333

Write text in each facet grid with discrete scale

I have the following data frame:

Parameter<-c("As","Hg","Pb")
Loc1<-c("1","10","12")   
Loc2<-c("3","14","9")  
Loc3<-c("5","12","8")
Loc4<-c("9","20","6")
x<-data.frame(Parameter,Loc1,Loc2,Loc3,Loc4)
x$Loc1<-as.numeric(x$Loc1)
x$Loc2<-as.numeric(x$Loc2)
x$Loc3<-as.numeric(x$Loc3)
x$Loc4<-as.numeric(x$Loc4)

I set up a plot with 4 facets, one for each location, to show the different heavy metal concentrations at each location.

melt<-melt(x, id=c("Parameter"))
ggplot(melt, aes(x = Parameter, y = value, fill = variable)) +
  geom_bar(stat = "identity", position = "dodge")+
  facet_grid(. ~ variable)

However, I would like to write text into each of the 4 facets. I tried geom_textbut couldn´t figure out how to get different text into each of the facet and place it at a specific location.

Upvotes: 2

Views: 668

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50718

The strip names in the facets are picked up from entries in column variable; therefore I would rename entries of variable prior to plotting.

Here is an example

x %>%
    gather(variable, value, -Parameter) %>%
    mutate(variable = sub("Loc", "Location ", variable)) %>%
    ggplot(aes(x = Parameter, y = value, fill = variable)) +
    geom_bar(stat = "identity", position = "dodge")+
    facet_grid(. ~ variable)

enter image description here


Update

If you want to add text to specific panels, I'd recommend storing the information is a new data.frame. To ensure that labels are placed inside the proper facets, you need to make sure that df.txt has a variable column that matches the entries from the variable column in your source data (i.e. the column which you use for facetting).

df.txt <- data.frame(
    variable = c("Loc1", "Loc2", "Loc3", "Loc4"),
    x = c(2, 2, 2, 2),
    y = c(1, 1, 1, 1),
    label = paste0("Text in facet ", 1:4))


x %>%
    gather(variable, value, -Parameter) %>%
    ggplot(aes(x = Parameter, y = value, fill = variable)) +
    geom_bar(stat = "identity", position = "dodge")+
    facet_grid(. ~ variable) +
    geom_text(data = df.txt, aes(x, y, label = label))

enter image description here

Upvotes: 2

Related Questions