[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 -----
> From: "Mahmood Naderan-Tahan" <mahmood.naderan using ugent.be>
> 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 <- read.csv('test.csv', header=T,row.names=1)
>> 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/ 
   https://www.psyctc.org/pelerinage2016/register-to-get-updates-from-pelerinage2016/

If you want an Emeeting, I am trying to keep them to Thursdays and my diary is at:
   https://www.psyctc.org/pelerinage2016/ceworkdiary/
Beware: French time, generally an hour ahead of UK.



More information about the R-help mailing list