Hi, in SPSS (vs 17) I am trying to create a before-after plot with lines for all cases, colored based on 3 categories. The data are organised as: 2 lines per case (before and after, labeled as 1 and 2), and labeled based on 3 categories of cases (labeled as 1, 2 and 3, per 2 lines per case). Using line plots I have managed to produce a before-after plot for all cases, but only with a seperate color for each case. I am also managing to create a before-after plot with 3 lines, which are all cases per category combined. Using scatter plots, I am managing to get something resembling a before-after plot, only without the connecting lines between the points, but managing to color the seperate cases based on category 1, 2 or 3. However, as described above, I want to have a before-after plot with lines colored based on three categories. I feel this should not be hard to do, but I’m just not managing. Many thanks in advance.
SPSS is a dead horse, here is a solution in tidy R. First, I simulate a data set like teh one described. Then I produce a case-level “spaghetti” plot. The last box first computes the mean per category and moment in order to produce an interaction plot.
These packages must first be installed:
library(tidyverse)
library(knitr)
library(haven)
n <- 60
Cat <- data_frame(Cat = as.factor(1:3),
beta_1_0 = c(2, 4, 6),
beta_1_1 = c(3, 2, 1))
Cases <- data_frame(Case = 1:n,
Cat = as.factor(rep(c(1,2,3), n/3))) %>%
left_join(Cat, by = "Cat") %>%
mutate(beta_0 = rnorm(n, beta_1_0, 1),
beta_1 = rnorm(n, beta_1_1, 1))
Data <-
expand.grid(Case = Cases$Case,
moment = c(0, 1)) %>%
as.tibble() %>%
left_join(Cases, by = "Case") %>%
mutate(measure = beta_0 + moment * beta_1,
Moment = as.factor(moment)) %>%
select(Case, Moment, Cat, measure)
Data %>% sample_n(10) %>% kable()
| Case | Moment | Cat | measure |
|---|---|---|---|
| 40 | 0 | 1 | 0.1808837 |
| 28 | 1 | 1 | 1.2415726 |
| 58 | 1 | 1 | 2.8068060 |
| 21 | 0 | 3 | 5.4906748 |
| 16 | 1 | 1 | 3.9753583 |
| 43 | 1 | 1 | 5.0055194 |
| 14 | 0 | 2 | 5.3360115 |
| 9 | 0 | 3 | 6.7953221 |
| 29 | 0 | 2 | 1.4672705 |
| 7 | 0 | 1 | 2.4078493 |
You may want to load your SPSS data file using:
Data <- read_sav("mydata.sav")
Data %>%
ggplot(aes(x = Moment,
y = measure,
group = Case)) +
facet_grid(~Cat) +
geom_line()
Data %>%
group_by(Cat, Moment) %>%
summarize(mean_measure = mean(measure)) %>%
ggplot(aes(x = Moment,
y = mean_measure,
col = Cat,
group = Cat)) +
geom_line()