Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different font size for every label in geom_text

Tags:

r

ggplot2

I have a bar plot made using ggplot2. I want to add label to each bar using geom_text such that the text size of the label is corresponds to the label. To do so I used the following code:

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
      geom_bar(stat="identity",position="dodge") + 
      geom_text(data = a, aes(label = mpg, size = mpg), 
                position = position_dodge(width=0.9))

This gave me a plot which looks like this: enter image description here

As you can see the label sizes are changing but the texts font size does not correspond to the size of the label. For the first bar the label is 15 and it is hardly visible. When I plot the same barplot with fixed text size as 15 the label is not as small as seen above. Following is the code and the plot generated using a fixed text size:

 a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

 p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
      geom_bar(stat="identity",position="dodge") + 
      geom_text(data = a, aes(label = mpg), 
                position = position_dodge(width=0.9), size = 15)  

enter image description here

Is there a way to make the size of the label consistent when different sizes are given for each label?

like image 383
SBista Avatar asked Mar 08 '23 01:03

SBista


1 Answers

Setting size to sort(a$mpg) does the trick

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
    geom_bar(stat="identity",position="dodge") + 
    geom_text(data = a, aes(label = mpg), 
              position = position_dodge(width=0.9), size = sort(a$mpg))

snap1

like image 85
parth Avatar answered Mar 11 '23 10:03

parth