在两个不同的数据框中绘制变量平均值,并在同一图中绘制

时间:2019-02-25 19:16:59

标签: r ggplot2

我目前有两个数据帧:dataframe5和dataframe 6。

cordova plugin add https://github.com/tkyaji/cordova-plugin-crypt-file.git

我已经在一个图中为两个数据框创建了一个时间图(总计与年) 我需要找到这两条线的平均值并将其绘制在同一张图中。temporalplot

我的尝试到目前为止没有奏效

head(dataframe5)
#Year     VegC    LittC   SoilfC   SoilsC    Total
#1 2013 1.820858 1.704079 4.544182 1.964507 10.03363
#2 2014 1.813573 1.722106 4.548287 1.964658 10.04863
#3 2015 1.776853 1.722110 4.553425 1.964817 10.01722
#4 2016 1.794462 1.691728 4.556691 1.964973 10.00785
#5 2017 1.808207 1.708956 4.557116 1.965063 10.03936
#6 2018 1.831758 1.728973 4.559844 1.965192 10.08578


head(dataframe6)
#  Year     VegC    LittC   SoilfC   SoilsC    Total
#1 2013 1.832084 1.736137 4.542052 1.964454 10.07474
#2 2014 1.806351 1.741353 4.548349 1.964633 10.06069
#3 2015 1.825316 1.729084 4.552433 1.964792 10.07164
#4 2016 1.845673 1.735861 4.553766 1.964900 10.10020
#5 2017 1.810343 1.754477 4.556542 1.965033 10.08640
#6 2018 1.814503 1.728337 4.561960 1.965191 10.07001

注意:两个数据框均包含88个观测值

2 个答案:

答案 0 :(得分:1)

这是一个通用答案,它将根据您的需要扩展到尽可能多的数据帧:

library(dplyr)
df_list = list(df5 = df5, df6 = df6)
library(dplyr)
big_df = bind_rows(df_list, .id = "source")
big_df = big_df %>% group_by(Year) %>% summarize_if(is.numeric, mean) %>%
  mutate(source = "Mean") %>%
  bind_rows(big_df)

ggplot(big_df, aes(x = Year, y = Total, color = source)) +
  geom_line()

enter image description here

更恰当地命名list将有助于图形标签。如果您确实有更多数据帧,强烈建议您在How to make a list of data frames上阅读答案。

使用此数据:

df5 = read.table(text = "Year     VegC    LittC   SoilfC   SoilsC    Total
1 2013 1.820858 1.704079 4.544182 1.964507 10.03363
2 2014 1.813573 1.722106 4.548287 1.964658 10.04863
3 2015 1.776853 1.722110 4.553425 1.964817 10.01722
4 2016 1.794462 1.691728 4.556691 1.964973 10.00785
5 2017 1.808207 1.708956 4.557116 1.965063 10.03936
6 2018 1.831758 1.728973 4.559844 1.965192 10.08578",
header = T)

df6 = read.table(text =
" Year     VegC    LittC   SoilfC   SoilsC    Total
1 2013 1.832084 1.736137 4.542052 1.964454 10.07474
2 2014 1.806351 1.741353 4.548349 1.964633 10.06069
3 2015 1.825316 1.729084 4.552433 1.964792 10.07164
4 2016 1.845673 1.735861 4.553766 1.964900 10.10020
5 2017 1.810343 1.754477 4.556542 1.965033 10.08640
6 2018 1.814503 1.728337 4.561960 1.965191 10.07001",
header = T)

答案 1 :(得分:0)

如果我理解正确,那么您想绘制2013年的10,054185

如果您每年都有一行,则可以创建一个新列,并将其添加到现有的ggplot中:

df <- dataframe5$Year
df$total5 <- dataframe5$Total
df$total6 <- dataframe6$Total
df$totalmean <- (df$total5+df$total6)/2

通过绘制df$totalmean,您应该获得直线的均值。只需在现有ggplot中通过+ Geometrie_line(...)添加行即可。