如何将第二个数据集添加到 R 中的点图中?

How do I add a second dataset to a dotplot in R?

我刚开始在统计课程中学习 R,并开始学习不同的绘图。

一个练习要求我们将两组数据绘制成一个点图,但我正在努力将第二组数据添加到其中。我正在使用 dotplot() 函数,这两个数据组是向量(我认为)。

我还不是很确定行话,所以请多多包涵。

smokers <- c(69.3, 56.0, 22.1, 47.6, 53.2, 48.1, 52.7, 34.4, 60.2, 43.8, 23.2, 13.8)
nonsmokers <- c(28.6, 25.1, 26.4, 34.9, 29.8, 28.4, 38.5, 30.2, 30.6, 31.8, 41.6, 21.1, 36.0, 37.9, 13.9)

dotplot(smokers, col = "blue", pch = 19)

points(nonsmokers, col = "red", pch = 18)

结果是吸烟者数据的点图,但图中未添加表示不吸烟者的红点。

如何将点添加到图中,或者有更好的方法吗?

PS。两组必须根据问题在同一行。

编辑 1:这是 lattice 包。我将它加载到另一个脚本上并忘记了。

或者使用 lattice 包,您可以将两个向量包装到一个数据框中并使用 ggplot2:

绘制它们
df <- data.frame(Value = c(smokers,nonsmokers),
                 Cat = c(rep("smokers",length(smokers)), rep("nonsmokers",length(nonsmokers))),
                 xseq = c(seq_along(smokers),seq_along(nonsmokers)))
library(ggplot2)
ggplot(df, aes(x = Cat, y = Value, color = Cat)) + geom_point()+xlab("")

EIT:在一条线上绘制两组

如果你想让两个组都在一行上,你可以这样做:

ggplot(df, aes(x = "points", y = Value, color = Cat)) + geom_point()+xlab("")

是您要找的吗?

一种方法是合并数据并使用公式作为 dotplot() 的参数。

smokers <- c(69.3, 56.0, 22.1, 47.6, 53.2, 48.1, 52.7, 34.4, 60.2, 43.8, 23.2, 13.8)
nonsmokers <- c(28.6, 25.1, 26.4, 34.9, 29.8, 28.4, 38.5, 30.2, 30.6, 31.8, 41.6, 21.1, 36.0, 37.9, 13.9)
library(lattice)
df1 <- data.frame(value=smokers)
df1$group <- "smokers"
df2 <- data.frame(value=nonsmokers)
df2$group = "nonsmokers"
data <- rbind(df1,df2)
dotplot(value ~ group, data = data)

...输出:

为了用group来区分不同的组,我们使用下面的形式dotplot()

aKey <- simpleKey(c("smokers","nonsmokers"))
dotplot(data$value,groups = data$group,key = aKey)

...输出: