gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:41:11 26 4
gpt4 key购买 nike

我想在同一图中将不同的行绘制为不同的线,以说明 3 个组的平均发展趋势:All、Men 和 Women。但是,我没有打印出其中一行,并且图例中没有填充行名。

我很高兴在 matplot 中找到解决方案或在 ggplot .

谢谢!

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")

最佳答案

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

关于r - 使用 matplot 在 R 中将不同的行绘制为不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com