TMOTTM TMOTTM - 2 months ago 6
R Question

How do I plot this data using R?

> aggregate(dat[, 3:7], by=list(dat$TRT), FUN=mean)
Group.1 DBP1 DBP2 DBP3 DBP4 DBP5
1 A 116.55 113.5 110.70 106.25 101.35
2 B 116.75 115.2 114.05 112.45 111.95


I wish to create a lines plot were the x-axis are the
names
(
DBP1
,
DBP2
, ...,
DBP5
).

It takes two seconds in Excel (I admit) and gives exactly what I want:
enter image description here

To be clear, the question is about getting the two rows of data into the plot, not about how they are displayed (i.e. with what line/point/color combination).

Answer

With dplyr, tidyr and ggplot2

Data

zz <- "Group.1   DBP1  DBP2   DBP3   DBP4   DBP5
A 116.55 113.5 110.70 106.25 101.35
B 116.75 115.2 114.05 112.45 111.95"

df <- read.table(text = zz, header = TRUE)

Load Required Packages

library(dplyr)
library(tidyr)
library(ggplot2)

Tidy

df_tidy <- df %>% 
    gather(key, value, -Group.1)

Plot

ggplot(data = df_tidy, aes(x = key, y = value)) +
    geom_line(aes(color = Group.1)) +
    ylim(90, 120)

Output

enter image description here

Comments