Using mtcars as an example, I've produced some violin plots. I wanted to add two things to this chart:
- for each group, list
n - for each group, sum a third variable (e.g.
wt)
I can do (1) with the geom_text code below although (n) is actually plotted on the x axis rather than off to the side.
But I can't work out how to do (2).
Any help much appreciated!
library(ggplot2)
library(gridExtra)
library(ggthemes)
result <- mtcars
ggplot(result, aes(x = gear, y = drat, , group=gear)) +
theme_tufte(base_size = 15) + theme(line=element_blank()) +
geom_violin(fill = "white") +
geom_boxplot(fill = "black", alpha = 0.3, width = 0.1) +
ylab("drat") +
xlab("gear") +
coord_flip()+
geom_text(stat = "count", aes(label = ..count.., y = ..count..))
You can add both of these annotations by creating them in your dataframe temporarily prior to graphing. Using the
dplyrpackage, you can create two new columns, one with the count for each group, and one with the sum ofwtfor each group. This can then be piped directly into your ggplot using%>%(alternatively, you could save the new dataset and insert it into ggplot the way you have it). Then with some minor edits to yourgeom_textcall and adding a second one, we can create the plot you want. The code looks like this:The new graph looks like this:
Alternatively, if you create a summary data frame named
result_sum, then you can manually add that into thegeom_textcalls.This gives you this:
The benefit to this second method is that the text isn't bold like in the first graph. The bold effect occurs in the first graph due to the text being printed over itself for all observations in the dataframe.