ayePete
ayePete

Reputation: 431

Plot Measurements Over Time [ggplot2]

I have a dataframe that looks like this:

   A1    A2    A3    A4    A5
   2     2     2     2     2
   3     3     3     3     4
   3     3     3     3     4
   1     1     2     2     1
   3     2     2     3     2
   4     4     4     3     4

I would like to plot multiple lines showing the trend from A1 to A5 (which are 5 measurements of the same variable over time) for each row (a patient) on a single graph using ggplot2 in r, with the y-axis as a categorical variable with values 1 - 5. I have gone through a lot of answers that suggest using melt from reshape2 or gather from tidyr, but they do not quite produce what I want. Would greatly appreciate any help.

Upvotes: 1

Views: 291

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50738

I'm not entirely clear on how you'd like to visualise your data but perhaps something like this?

library(tidyverse)
df %>%
    rowid_to_column("patient") %>%
    mutate(patient = factor(patient)) %>%
    gather(key, val, -patient) %>%
    ggplot(aes(x = key, y = val, colour = patient, group = patient)) +
    geom_line()

enter image description here

df %>%
    rowid_to_column("patient") %>%
    mutate(patient = factor(patient)) %>%
    gather(key, val, -patient) %>%
    ggplot(aes(x = key, y = val, colour = patient, group = patient)) +
    geom_line() +
    facet_wrap(~ patient)

enter image description here


Sample data

df <- read.table(text =
    "  A1    A2    A3    A4    A5
   2     2     2     2     2
   3     3     3     3     4
   3     3     3     3     4
   1     1     2     2     1
   3     2     2     3     2
   4     4     4     3     4", header = T)

To remove the x-axis you can do

df %>%
    rowid_to_column("patient") %>%
    mutate(patient = factor(patient)) %>%
    gather(key, val, -patient) %>%
    ggplot(aes(x = key, y = val, colour = patient, group = patient)) +
    geom_line() +
    facet_wrap(~ patient) +
    theme(
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

enter image description here

Mind you, it might not be very sensible to remove the x axis.

Upvotes: 2

Related Questions