简体   繁体   中英

ggplot for different year categories

I am really struggling with the plots in R. I have to make a plot of logmx versus the age of males in different years in the same plot for males. In this plot there must be 4 lines for "1870-1879", "1940-1949", "1960-1969", "1980-1989" I made 4 differents subsets with these specific years and tried to combine them but I am new in R and I do not know what I am doing wrong. I saw lots of similar answers but I could not solve it.I need to make it with ggplot2 package.

males11<-males[445:1555,1:3]
males12<-males[4885:5995, 1:3]
males13<-males[9325:10435, 1:3]
males14<-males[13765:14653, 1:3] #for the subsets

d1 <- data.frame(males11$Age, log(males11$mx), males11$Year)
d2 <- data.frame(males12$Age, log(males12$mx), males12$Year)
d3 <- data.frame(males13$Age, log(males13$mx), males13$Year)
d4 <- data.frame(males14$Age, log(males14$mx), males14$Year)

ggplot()
+ geom_line(aes(males11$Age, log(males11$mx), colour=males11$Year), d1) +
geom_line(aes(males12$Age, log(males12$mx), colour=males12$Year), d2) +
geom_line(aes(males13$Age, log(males13$mx), colour=males13$Year), d3) +
geom_line(aes(males14$Age, log(males14$mx), colour=males14$Year), d4)

You should build a factor in your original data frame and group by that, similar to this:

males$group <- cut(males$Year, 
                   breaks=seq(1799, 2099, 10), 
                   dig.lab=4)
library(ggplot2)
ggplot(males[males$group %in% c("(1869-1879]", "(1939-1949]", "(1959-1969]", "(1979-1989]"), ], 
       aes(Age, mx, colour=group)) + 
  geom_line() + 
  scale_y_log10()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM