使用matplot在R中将不同的行绘制为不同的线

Plotting different rows as different lines in R with matplot

我想将不同的行绘制为同一图中的不同线,以说明 3 个组的平均发展的运动:所有、男性和女性。但是,我没有打印其中一行,并且图例中没有填充行名。

我很高兴在 matplotggplot 中找到解决方案。

谢谢!

代码:

matplot(t(Market_Work), type = 'l', xaxt = 'n', xlab = "Time Period", ylab = "Average", main ="Market Work")

legend("right", legend = seq_len(nrow(Market_Work)), fill=seq_len(nrow(Market_Work)))

axis(1, at = 1:6, colnames(Market_Work))

数据:

       2003-2005   2006-2008   2009-2010   2011-2013   2014-2016   2017-2018
All     31.48489    32.53664    30.41938    30.53870    31.15550    31.77960
Men     37.38654    38.16698    35.10247    35.65543    36.54855    36.72496
Women   31.48489    32.53664    30.41938    30.53870    31.15550    31.77960


> dput(Market_Work)
structure(list(`2003-2005` = c(31.4848853173555, 37.3865421137, 
31.4848853173555), `2006-2008` = c(32.5366433161048, 38.1669798351148, 
32.5366433161048), `2009-2010` = c(30.4193794808191, 35.1024661973137, 
30.4193794808191), `2011-2013` = c(30.5387012166381, 35.6554329405739, 
30.5387012166381), `2014-2016` = c(31.1555032381292, 36.5485451138792, 
31.1555032381292), `2017-2018` = c(31.7795953402235, 36.7249638612854, 
31.7795953402235)), row.names = c("All", "Men", "Women"), class = "data.frame")

这是一个 ggplot2 的例子。我更改了您的一些数据,因为您的原始数据中有两行相同。

library(tidyverse)
df <- structure(list(`2003-2005` = c(31.4848853173555, 37.3865421137, 
30.4848853173555), `2006-2008` = c(32.5366433161048, 38.1669798351148, 
30.5366433161048), `2009-2010` = c(30.4193794808191, 35.1024661973137, 
33.4193794808191), `2011-2013` = c(30.5387012166381, 35.6554329405739, 
33.5387012166381), `2014-2016` = c(31.1555032381292, 36.5485451138792, 
30.1555032381292), `2017-2018` = c(31.7795953402235, 36.7249638612854, 
30.7795953402235)), row.names = c("All", "Men", "Women"), class = "data.frame")
df2 <- as.data.frame(t(df))
df2$Year <- rownames(df2)
df2%>% pivot_longer( c(All,Men,Women), names_to = "Category") %>% 
      ggplot(aes(x = Year, y = value)) + geom_line(aes(group = Category, color = Category))