0

I have been working on data visualization of a dataset.

I've found a baseplot version that allow me to visualize the effect of pre- and post treatment.

I would like to know if there is ggplot version of this plot.

> dput(data)
structure(list(ID = c("far001", "far002", "far003", "far004", 
"far005", "far006", "far007", "far008", "far009", "far010"), 
    HBA1Cpre = c(7, 8, 7.5, 9, 8.1, 7.9, 7.3, 7.4, 7.8, 7.1), 
    HBA1Cpost = c(6.5, 6.6, 6.8, 7, 6.3, 6.9, 6.7, 7.1, 7, 6.5
    )), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))
matplot(t(data.frame(HBA1Cpre,HBA1Cpost)), type="b", xaxt="n", pch=19, col=1, lty=1, ylab="HBAIC(%)") 

1 Answer 1

1

Here are two approaches.

1) Use geom_segment to specify the start and end of each point, with a geom_point for the starts and another for the ends.

library(ggplot2)
ggplot(data, aes(x = "HBA1Cpre", xend = "HBA1Cpost",
                 y = HBA1Cpre, yend = HBA1Cpost)) +
  geom_segment() +
  geom_point() +
  geom_point(aes(x = "HBA1Cpost", y = HBA1Cpost)) +
  scale_x_discrete(limits = c("HBA1Cpre", "HBA1Cpost"))

enter image description here

2) Do a little reshaping to put the data in longer form, then map the time status to x. (Here there's an extra step making the time status into a factor so it can be displayed in non-alphabetical order. Could also be accomplished by manipulating scale_x_discrete like above.)

library(dplyr)
data %>%
  pivot_longer(-ID, names_to = "time", values_to = "val") %>%
  mutate(time = factor(time, levels = c("HBA1Cpre", "HBA1Cpost"))) %>%
  ggplot(aes(x = time, y = val, group = ID)) +
  geom_line() +
  geom_point()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.