组合来自不同两个数据帧的两个折线图

时间:2019-12-01 15:21:20

标签: r ggplot2 linegraph

我有两个线形图显示:一个显示四个采样中六个物种的下降,另一个显示相同六个物种的总下降。我想创建一个图,该图具有单独显示的六个物种和总衰落。

下面是我的六个物种数据框的示例

 Week       Species      Unit
   1           A           13
   1           B           24
   2           B           15
   2           C           32
   3           C           43
   4           D           32

下面是我用来创建显示六种物种下降趋势的折线图的代码

Species_Change<-ggplot(Total_Count, aes(x=Week, y=Unit, group=Scientific.name, color=Scientific.name)) +
  geom_point()+
  geom_line()+
  scale_colour_manual(values = c("yellow", "orange 2", "purple", "maroon 2", "blue", "purple 4","green"))+
  ylab("Total number of floral units over the four habitats")+
  xlab("Sampling round")+
  labs(col="Plant species")

下面是数据框的样本,显示了整个采样周期内所有物种的总数

Week           Unit
 1              32
 2              55
 3              73
 4              62

下面显示了用于创建第二个折线图的代码,该图显示了采样周期内所有物种的总数

Total_Change<-ggplot(Total_Round, aes(x=Week, y=Unit, )) +
  geom_point()+
  geom_line()+
  ylab("Total number of floral units over the four habitats")+
  xlab("Sampling round")+
  labs(col="Plant species")

1 个答案:

答案 0 :(得分:1)

我不确定这是否是您想要的,但是您可以在Total_count data.frame中添加一个名为“ total”的新物种。使用您提供的数据:

数据
dput(Total_Count)
structure(list(Week = c(1L, 1L, 2L, 2L, 3L, 4L), Species = structure(c(1L, 2L, 2L, 3L, 3L, 4L), .Label = c("A", "B", "C", "D"), class = "factor"), Unit = c(13L, 24L, 15L, 32L, 43L, 32L)), row.names = c(NA, -6L), class = "data.frame")
dput(Total_Round)
structure(list(Week = c(1, 2, 3, 4), Unit = c(32, 55, 73, 62)), class = "data.frame", row.names = c(NA, -4L))
Total_Round$Species <- factor(rep("Total",nrow(Total_Round))) # Create total species
df <- rbind(Total_Count, Total_Round) # Merge both data.frames
AllwithTotal_Species_Change<-ggplot(df, aes(x=Week, y=Unit, group=Species, color=Species)) +
  geom_point()+
  geom_line()+
  scale_colour_manual(values = c("yellow", "orange 2", 
                                 "purple", "maroon 2", 
                                 "blue", "purple 4",
                                 "green"))+
  ylab("Total number of floral units over the four habitats")+
  xlab("Sampling round")+
  labs(col="Plant species")
AllwithTotal_Species_Change

plotresult

希望这会有所帮助!