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

问题描述 投票:1回答:1

我想在同一幅图中将不同的行绘制为不同的线,以说明三个组(所有人,男人和女人)的平均发展情况。但是,我没有打印出任何一行,并且图例没有用行名填充。

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

谢谢!

enter image description here

代码:

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")
r plot rows legend
1个回答
0
投票

这里是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))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.