user3067851
user3067851

Reputation: 534

Change relative font size for chart label in ggplot 2 R

Using the mtcars dataset, I wrote the following code which shows text labels in the chart with font sizes that depend on their counts of 'carb'. I would like to enlarge the relative font sizes of these labels because the smallest - count of 3 on the y-axis- is too small. I've found similar post, but nothing directly addressing this issue.

 ggplot(mtcars, aes(carb)) +
   stat_count(aes(y = ..count..),  
      show.legend = F, geom = "text") +
      element_text(aes(size = ..count.., label = ..count..))

Upvotes: 1

Views: 1138

Answers (1)

Stibu
Stibu

Reputation: 15927

The actual size of the numbers that are printed is controlled by scale_size_continuous. The scale takes the argument range, which defines the sizes to be used for the smallest and largest object. By default, range = c(1,6). You can play with the two numbers until you get the desired result.

Default values:

ggplot(mtcars, aes(carb)) +
  stat_count(aes(y = ..count..),  
             show.legend = F, geom = "text") +
  element_text(aes(size = ..count.., label = ..count..)) +
  scale_size_continuous(range = c(1, 6))

enter image description here

Enlarge small numbers, but keep maximum size the same:

ggplot(mtcars, aes(carb)) +
  stat_count(aes(y = ..count..),  
             show.legend = F, geom = "text") +
  element_text(aes(size = ..count.., label = ..count..)) +
  scale_size_continuous(range = c(3, 6))

enter image description here

Enlarge all numbers:

ggplot(mtcars, aes(carb)) +
  stat_count(aes(y = ..count..),  
             show.legend = F, geom = "text") +
  element_text(aes(size = ..count.., label = ..count..)) +
  scale_size_continuous(range = c(4, 12))

enter image description here

Upvotes: 1

Related Questions