strengejacke / sjPlot

sjPlot - Data Visualization for Statistics in Social Science
https://strengejacke.github.io/sjPlot
606 stars 91 forks source link

weightBy does not seem to work in sjp.frq, sjt.frq, others?? #108

Closed ebergel closed 8 years ago

ebergel commented 8 years ago

these minimal examples are producing some errors

sjp.frq(varCount = c('a','b','c'), weightBy = c(1,2,3) )

Error in $<-.data.frame(*tmp*, "valid.prc", value = c(Inf, NA)) : replacement has 2 rows, data has 1 In addition: Warning messages: 1: NAs introduced by coercion 2: NAs introduced by coercion 3: NAs introduced by coercion

sjp.frq(varCount = c(1,2,3) , weightBy = c(1,2,3) )

Warning messages: 1: Removed 1 rows containing missing values (position_stack). 2: Removed 2 rows containing missing values (geom_text).

I am doing somthing wrong?

Cheers,

Eduardo

sjPlot commented 8 years ago

According to your error: Unfortunately, you can't weight character vectors, thus you have to convert your vector to numeric values (e.g. using sjmisc::to_value).

According to your second example: The weighting works. The warning message is because text labels are positioned outside of the plot area. ggplot2 has an unhappy default positioning of text geoms, which directly stick at other geoms, thus you have overlapping bars and value labels. To avoid this, I'm adding a small percentage to the y-position to the value labels, which rounds up to 1 unit in your example - an y-axis ranging from 0 to 2 leaves not much room for one additional unit. ;-)

I asked Hadley Wickham if he could change the defaults of text geom when they have the same y-pos as other geoms (to avoid overlapping), but he won't fix and said that one should manually add a small offset to the y-pos of text geoms. This is easy to do if you set up your own plot by try and error, but it's hard to determine this offset in a generic way for plotting functions, like those in my package...

I'll see if I can improve the y-offset-calculation in some way.

ebergel commented 8 years ago

Thanks for the detailed answer! I could not manage to make weights work. I expanded the dataset and it works just fine. Thanks

sjPlot commented 8 years ago

weighting works fine for numeric vectors, so you have to convert your character vectors to numeric first, see this example:

library(sjPlot)
library(sjmisc)

set.seed(1)

x <- sample(letters[1:5], size = 20, replace = T)
w <- runif(n = 20)

sjp.frq(to_value(x), y.offset = .1)
table(x)

sjp.frq(to_value(x), weightBy = w, y.offset = .1)
xtabs(w ~ x)
round(xtabs(w ~ x))
sjPlot commented 8 years ago

ok, weighting now accepts character vectors. I'm commiting the changes soon.