2

Consider the simple example:

library(ggplot2)

head(mtcars)


# create the plot
ggplot(mtcars, aes(factor(cyl))) + geom_bar() + theme_bw() +
      theme(strip.text.x = element_text(size = 20, face="bold"))+
      xlab("number of cyl") + ylab("Count") 

Now we can obtain the average $mpg per cyl with:

aggregate(mpg ~ cyl, data = mtcars, FUN=mean)

How can I put these average values into the x-axis so that they appear below the corresponding cyl. Can one draw a table and somehow write that this is the ...average mpg per cyl...

3
  • 1
    maybe this helps: stackoverflow.com/questions/16680063/… Commented Jun 8, 2016 at 9:04
  • Is there a specific reason to use facet_grid instead of ggtitle() to put a title on the plot? This may add unneccessary complexity to a potential answer. Commented Jun 8, 2016 at 9:07
  • No, lets remove it Commented Jun 8, 2016 at 9:09

1 Answer 1

1

Here is a simple way to do it by rewriting the factor level names:

(Note that this is safe only as long as aggregate generates it table in the same order as the factor level names and without any gaps - which seems like it should be the case, but one would have to investigate to make sure. It might be safer to code it as a loop and look at the level names to make sure they match up correctly)

library(ggplot2)

head(mtcars)

adf <- aggregate(mpg ~ cyl, data = mtcars, FUN=mean)
mtcars$fcyl <- factor(mtcars$cyl)
levels(mtcars$fcyl) <- sprintf("%d \n %.1f",adf$cyl,adf$mpg)

# create the plot
ggplot(mtcars, aes(fcyl)) + geom_bar() + theme_bw() +
  theme(strip.text.x = element_text(size = 20, face="bold"))+
  xlab("number of cyl") + ylab("Count") 

yielding:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Any comments?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.