Gurt
Gurt

Reputation: 25

Combine scatterplot and barplot, then lapply

I am trying to add a scatterplot and a barplot within the same plot area with ggplot. The scatterplot should be averages of var. '1' over var.'2' for one dataset, and the barplot should be the average value of '1' over my control dataset.

My data looks like this:

> dput(lapply(ubbs6, head))
list(structure(c(96L, 96L, 100L, 88L, 93L, 100L, 61L, 61L, 70L, 
40L, 58L, 70L, 7807L, 7357L, 7695L, 6400L, 6009L, 7735L), .Dim = c(6L, 
3L), .Dimnames = list(NULL, c("1", "2", "3"))), structure(c(99L, 
96L, 100L, 96L, 96L, 96L, 66L, 67L, 70L, 63L, 57L, 62L, 7178L, 
6028L, 6124L, 6082L, 6873L, 5629L, 31L, 27L, 60L, 42L, 12L, 18L
), .Dim = c(6L, 4L), .Dimnames = list(NULL, c("1", "2", 
"3", "4"))), structure(c(99L, 95L, 95L, 100L, 96L, 95L, 69L, 
58L, 56L, 70L, 61L, 65L, 6067L, 6331L, 6247L, 5988L, 7538L, 6162L, 
50L, 36L, 67L, 10L, 55L, 70L), .Dim = c(6L, 4L), .Dimnames = list(
    NULL, c("1", "2", "3", "4"))))

Example of what I've tried so far:

 aggregate(ubbs6[[2]][,'1'], list(ubbs6[[2]][,'2']), mean)

m162 <- aggregate(ubbs6[[2]][,'1'], list(ubbs6[[2]][,'2']), mean)
m163 <- aggregate(ubbs6[[3]][,'1'], list(ubbs6[[3]][,'2']), mean)
m161 <- mean(ubbs6[[1]][,'1'])

ggplot(m162, aes_(x = m162[,'Group.1'], y = m162[,'x']))+
  geom_point()+
  geom_smooth(method = 'lm', formula = 'y ~ sqrt (x)')

I would like to do two things:

  1. add a barplot of one x,y value of my control set (ubbs6[[1]])

  2. throw this into a lapply structure so I can do this for 11 similar datasets

    Any help would be greatly appreciated!

**EDIT: edited out specific details that aren't needed for others to understand the code **

Upvotes: 0

Views: 324

Answers (1)

Roman
Roman

Reputation: 17648

Saving your data in d, you can try

ggplot(as.data.frame(d[[2]]),aes(age, FPAR) ) + 
   coord_cartesian(ylim = c(90,100)) +
   geom_point() + 
   geom_smooth(method = 'lm', formula = 'y ~ sqrt (x)') + 
   geom_col(data=data.frame(x=max(as.data.frame(d[[2]])$age),
                       y=mean(as.data.frame(d[[1]])$FPAR)),
                       aes(x,y), inherit.aes = FALSE)

enter image description here

You have to use coord_cartesian to specify the y-limits and inherit.aes = FALSE. Otherwise the bar is not correctly drawn.

When you have to combine your second and third dataframe in one plot, you can try

library(tidyverse)
d %>% 
  .[2:3] %>% 
  map(as.data.frame) %>% 
  bind_rows(.id = "id") %>% 
  mutate(max = max(age),
         Mean = mean(d[[1]][1])) %>% 
  ggplot(aes(age, FPAR, color=id)) +
   geom_point() + 
   geom_smooth(method = 'lm', formula = 'y ~ sqrt (x)', se=FALSE) + 
    geom_col(data = . %>% distinct(max, Mean),
             aes(max, Mean), inherit.aes = FALSE)

enter image description here

Upvotes: 1

Related Questions