1
votes

I've just started learning R in a statistics course and started learning the different plots.

One exercise requires us to plot two groups of data into a dot-plot, but I'm struggling to add the second group of data to it. I'm using the dotplot() function, and the two data groups are vectors (I think).

I'm not entirely sure on the lingo yet, so please bear with me.

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)

The result is a dotplot of the smoker-data, but the red points for nonsmokers aren't added to the plot.

How do I add the points to the plot, or are there better ways to do it?

PS. The two groups must be on the same line according to the problem.

Edit 1: This is the lattice package. I'd loaded it on another script and forgot.

2
Are you using the dotplot function from the lattice package? Or something else? It would be helpful if you include the library statement in your code so that we know. - G5W
Yes this is from the lattice package. I'd loaded it earlier and forgot. - Esye
Do you want both lines of dots together, or on separate lines? - G5W
The exercise says the dots for the two groups must be on the same line. - Esye

2 Answers

2
votes

Alternatively to the use of lattice package, you can wrap your two vectors into a single dataframe and plot them using 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("")

enter image description here

EIT: Plotting two groups on a single line

If you want to have both group on a single line you can do:

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

enter image description here

Is it what you are looking for ?

2
votes

One approach is to combine the data and use a formula as the argument to 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)

...and the output:

enter image description here

To use group to distinguish the groups by color, we use the following form of dotplot().

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

...and the output:

enter image description here