简体   繁体   English

将因子水平段打印到基本 R 中的条形图中

[英]Print segments for factor levels into stripchart in base R

I have a dataframe with a numerical variable and a factor variable, like this:我有一个带有数值变量和因子变量的 dataframe,如下所示:

set.seed(123)
df <- data.frame(
  numbers = c(rnorm(50, 3), runif(50)),
  levels = sample(LETTERS[1:5], 100, replace = T)
)

What I'd like to do is a stripchart that plots df$numbers against df$levels and inserts vertical segment lines representing the mean for each level.我想要做的是一个条形图,它绘制df$numbersdf$levels插入代表每个级别平均值的垂直线段。

stripchart(df$numbers ~ df$levels, method = "jitter")

Obviously, I could insert the means line for each level separately, eg:显然,我可以分别为每个级别插入均值行,例如:

segments(x0 = mean(df$numbers[df$levels=="A"]), y0 = 1-0.3, y1 = 1+0.3, col = "red" )

And so on for all other levels, which is tedious if you have multiple levels.对于所有其他级别,依此类推,如果您有多个级别,这会很乏味。 So I've tried this for loop:所以我试过这个for循环:

for(i in seq(unique(df$levels))){
  segments(x0 = mean(df$numbers[df$levels==i]),
           y0 = i - 0.3,
           y1 = i + 0.3,
           col = "red", lty = 3, lwd = 2)
}

But that doesn't print anything (and doesn't throw an error either).但这不会打印任何东西(也不会引发错误)。 What's the cleanest and simplest code to insert the means segments?插入均值段的最干净和最简单的代码是什么?

As the 'levels' column is factor , use levels to get the levels of the factor 'un1', then loop over the sequence of unique elements, get the mean of the 'numbers' where the levels column is the unique value to create the segments由于 'levels' 列是factor ,使用levels来获取factor 'un1' 的级别,然后遍历唯一元素的序列,获取 'numbers' 的mean ,其中levels列是创建唯一值的唯一值segments

un1 <- levels(df$levels)
for(i in seq_along(un1)){
 segments(x0 = mean(df$numbers[df$levels==un1[i]]),
       y0 = i - 0.3,
       y1 = i + 0.3,
       col = "red", lty = 3, lwd = 2)
}

在此处输入图像描述

-checking the mean -检查mean

with(df, tapply(numbers, levels, FUN = mean))
#      A        B        C        D        E 
#1.390202 1.541655 2.086605 2.377122 1.663159 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM