0

When labelling axis ticks I'd like to add other information from the dataframe in parentheses. For example, using code snippet below I'd like to automatically include the information on Area in parentheses next to the label X. In other words, the label might say 'Chicago (45)' instead of just 'Chicago'. I know I can do this manually by setting labels in scale_x_discrete. However, can I do this automatically? My dataset has a large number of entries so I would like to avoid doing this manually.

dataset <- data.frame(Area = sample(c(NA, 1:100), 3, rep = TRUE),
                      Y = rnorm(3), X = c("Chicago","New York", "Orlando"))
ggplot(dataset, aes(X, Y)) + geom_point()
1
  • 1
    You could do something like this on the fly: aes(paste0(X, "\n(", round(Area), ")"), Y) Commented May 27, 2019 at 18:34

1 Answer 1

1

You can build a new column with your desired ticks labels:

library(dyplr)
library(stringr)
library(ggplot2)
dataset = dataset %>% mutate(label = str_c(X, " (", Area, ")"))

Then use the column label in the aesthetics

ggplot(dataset, aes(label, Y)) + geom_point()
Sign up to request clarification or add additional context in comments.

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.