Trying to use a value in the ggplots title

Viewed 24

I have been trying to put the value "Site 1" in a title for a ggplot, but I can't work out the syntax.

I have a tibble called g:

A tibble: 1 × 2
  Site       n
  <chr>  <int>
1 Site 1    27

And using this code:

ggplot(g,aes(Site, n), fill=as.factor(Site))+
  geom_col(aes(fill = Site), show.legend = FALSE) +
  geom_text(aes(label = n), size = 3)+
  labs(title=glue("adfadf", .$Site))

To create this plot:

enter image description here

I want the title to say "This is a plot for Site", but I am doing something wrong. I have tried different things other than the above, but I get errors like

"Error in force(..2) : object '.' not found"

for my version of the code. What is wrong in the title syntax?

1 Answers

You can just use ggtitle to add the title to your plot.

library(ggplot2)

ggplot(g, aes(Site, n), fill = as.factor(Site)) +
  geom_col(aes(fill = Site), show.legend = FALSE) +
  geom_text(aes(label = n), size = 3) +
  ggtitle("This is a plot for Site 1")

Output

enter image description here

Or you can paste the value to the phrase in ggtitle:

ggplot(g, aes(Site, n), fill = as.factor(Site)) +
  geom_col(aes(fill = Site), show.legend = FALSE) +
  geom_text(aes(label = n), size = 3) +
  ggtitle(paste0("This is a plot for ", g$Site[1]))

Data

g <- structure(list(Site = "Site 1", n = 27L), class = "data.frame", row.names = "1")
Related