Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand top of scale/axis to include text

Tags:

r

ggplot2

I'm trying to annotate the highest value in each facet of a graph.

I can't figure out how to remove extra space at the bottom of the y axis without clipping the text above the highest value.

A) Is there a non-symmetrical version of scale_y_continuous(expand=c(0,0))?

B) Or, is there a way to make ggplot include text as part of the graph range?

# a simple dataset
count <- 40
data <- data.frame(
  category = sample(LETTERS[1:3], count, TRUE),
  x = rnorm(count),
  y = abs(rnorm(count))
)

# find the highest value in each category
require(plyr)
data <- data[order(-data$y),]
topValues <- ddply(data, .(category), head, 1)

require(ggplot2)
ggplot(data) +
  geom_line(aes(x=x, y=y)) +
  geom_text(data=topValues, aes(x=x, y=y, label=y)) + # label the highest y value
  # add vjust=-1 to put text above point if possible
  facet_grid(category ~ ., scale="free") +
  scale_x_continuous(expand=c(0,0)) +
  scale_y_continuous(expand=c(0,0))

sample output

like image 724
sharoz Avatar asked Jan 05 '14 18:01

sharoz


1 Answers

The answer comes thanks to baptiste.

Just add this call to the plot to make a blank point at the top of the text:

geom_blank(data=topValues, aes(x=x, y=y*1.1, label=y))
like image 53
sharoz Avatar answered Oct 15 '22 15:10

sharoz