[R] Weighted violin chart

Chris Evans chr|@ho|d @end|ng |rom p@yctc@org
Tue Apr 13 08:32:55 CEST 2021

```
----- Original Message -----
> To: r-help using r-project.org
> Sent: Monday, 12 April, 2021 21:01:18
> Subject: [R] Weighted violin chart

> Hi,
>
> I would like to know if it is possible to plot a weighted violin chart with R.
> Currently, I have
>
>
>> library(ggplot2)
>> mydata
>     V1 V2 V3
> P1 73.6 50  R
> P2 75.2 20  R
> P3  6.5  5  R
> P4 41.4 10  C
> P5  5.4 10  C
> P6 18.8  5  C
>> p <- ggplot(mydata, aes(x=V3, y=V1)) + geom_violin(trim=FALSE)
>> p + geom_dotplot(binaxis='y', stackdir='center', dotsize=1)
>
> I would like to use V2 as the weight vector. Any idea about that?
>
>
>
> Regards,
> Mahmood

There are, of course, nice ways to do this using base R but I am trying to convert to using tidyverse.
Here is one:

### use tribble to create a tibble rowwise
tribble(
~V1, ~V2, ~V3,
73.6, 50, "R",
75.2, 20, "R",
6.5, 5, "R",
41.4, 10, "C",
5.4, 10, "C",
18.8, 5, "C") -> myData

### use tidyr::uncount() to get to the data you want
myData %>%
uncount(V2) -> tibWtdMyData

### plot it
ggplot(tibWtdMyData,
aes(x=V3, y=V1)) +
geom_violin(trim=FALSE) +
geom_dotplot(binaxis='y', stackdir='center', dotsize=1)

Of course, with so many identical values, I'm not sure a violin plot makes sense but perhaps you
were showing us a small subset of your data.

I have a nasty feeling there is a way of weighting things within ggplot.  If so, I am sure someone
will tell us.

For future, it's much easier for us to reply if you put small bits of data like your myData into
your Email using dput.  The output from dput doesn't look terribly human friendly but unless it
is mangled by HTML Emailing, it is wonderfully human friendly to use!

Very best (all),

Chris

--
Chris Evans (he/him) <chris using psyctc.org> Visiting Professor, University of Sheffield <chris.evans using sheffield.ac.uk>
I do some consultation work for the University of Roehampton <chris.evans using roehampton.ac.uk> and other places
but <chris using psyctc.org> remains my main Email address.  I have a work web site at:
https://www.psyctc.org/psyctc/
and a site I manage for CORE and CORE system trust at:
http://www.coresystemtrust.org.uk/
I have "semigrated" to France, see:
https://www.psyctc.org/pelerinage2016/semigrating-to-france/