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:
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)
Is there a way to make the size of the label consistent when different sizes are given for each label?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With