[R] ggplot2: Plot multiple lines using stacked data.
Sorkin, John
j@ork|n @end|ng |rom @om@um@ry|@nd@edu
Fri Dec 6 02:37:57 CET 2024
I am trying to use ggplot2 to create a figure with multiple lines, one line for each value of the variable Day. Each group of data for Day requires seven lines. The dataframe has data for 4 days and thus 4*7=28 lines.
I can create a plot, but the plot only contains dots. The dots for each day should be connected each day's data by a different line. There should be a total of four lines on the graph
mydata <-structure(list(Day = c("25", "25", "25", "25", "25", "25", "25",
"26", "26", "26", "26", "26", "26", "26", "27", "27", "27", "27",
"27", "27", "27", "28", "28", "28", "28", "28", "28", "28"),
AQIGroup = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L,
4L, 5L, 6L, 7L), levels = c("Good", "Moderate", "UnForSome",
"UH", "VUH", "Haz1", "Hax2"), class = "factor"), Freq = c(98.05,
0.37, 0.27, 0.17, 0.26, 0.5, 0.38, 93.34, 4.34, 0.75, 0.42,
0.44, 0.44, 0.27, 89.57, 7.8, 0.98, 0.38, 0.5, 0.52, 0.25,
80.43, 13.33, 3.85, 0.76, 0.86, 0.28, 0.49)), class = "data.frame", row.names = c(NA, -28L))
# You can see that the data are stacked, one day on top of the next.
# Each day requires seven lines.
mydata
# Load ggplot2
if(!require(ggplot2)) {install.packages(ggplot2)}
library(ggplot2)
# Create a graph, with multiple lines, one line for each value of Day.
ggplot(mydata, aes(AQIGroup,Freq,color=Day)) +
geom_point()+
geom_line(aes(AQIGroup,Freq))
Thank you,
John
John David Sorkin M.D., Ph.D.
Professor of Medicine, University of Maryland School of Medicine;
Associate Director for Biostatistics and Informatics, Baltimore VA Medical Center Geriatrics Research, Education, and Clinical Center;
PI Biostatistics and Informatics Core, University of Maryland School of Medicine Claude D. Pepper Older Americans Independence Center;
Senior Statistician University of Maryland Center for Vascular Research;
Division of Gerontology and Paliative Care,
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
Cell phone 443-418-5382
More information about the R-help
mailing list