Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

I have used the following ggplot command:

ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)

  + scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2))

  + facet_grid(hospital ~ .)

  + theme(panel.background = theme_blank())

to produce

alt text

I'd like to change the facet labels, however, to something shorter (like Hosp 1, Hosp 2...) because they are too long now and look cramped (increasing the height of the graph is not an option, it would take too much space in the document). I looked at the facet_grid help page but cannot figure out how.

1 Answer

0 votes
by

To change the facet labels, you can rename the factors of the variable used for faceting.

For example:

data(mtcars)

mtcars$cyl <- as.factor(mtcars$cyl)

levels(mtcars$cyl) <- c("Four", "Six", "Eight")

levels(mtcars$cyl)

Output:

[1] "Four"  "Six"   "Eight"

To avoid changing the underlying data, you can use the following :

ggplot(transform(mtcars, cyl= c("Four", "Six", "Eight")[as.numeric(cyl)]), aes(mpg)) + stat_bin() + facet_grid(cyl ~ .)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers

500 comments

108k users

Browse Categories

...