Skip to content

ggplot aesthetics error for looped multiplot using multiple input - store multiple dataframes in ggplot object? #4246

@rb643

Description

@rb643

I'm currently having an issue generating multiple ggplot objects into a list that I can subsequently order nciely with ggarrange/grid.arrange. I'm away of a previous issue mentioning this: #2139

From that I've figured out that the aesthetics errors occurs because only the data of the final figure in the list is stored properly. In my particular scripts however my ggplot object have multiple layers that are dependent on different dataframe and it seems only the main dataframe is stored? Is there a way around that to force the data to be stored within the object of each figure?

I've already tried storing all the dataframes I'm subsetting in a list as well and feeding those in, but I still get the aesthetics error of mismatching x and y axes when I try to plot any but the last figure in the list.

`figlist <- list()
df <- list()
newdat <- list()

for(i in 1:length(unique(data.dxxx$dx))){
diag <- as.character(unique(data.dxxx$dx)[i])
df[[i]]=data.dxxx[data.dxxx$dx %in% diag,]
quantile_lme <- lme(quantile ~ age_days_centered + sex, data= df[[i]], random=~1|participant)
newdat[[i]] <- expand.grid(sex=unique( df[[i]]$sex),
age_days_centered=c(min( df[[i]]$age_days_centered),
max( df[[i]]$age_days_centered)))

p <- ggplot() +
geom_point(data = df[[i]], aes(x=age_days_centered, y=quantile, fill=sex),size=3,shape=21, alpha = 0.5) +
geom_line(data = df[[i]], aes(x=age_days_centered, y=predict(quantile_lme), group=participant, size="Subjects")) +
geom_line(data = newdat[[i]], aes(x=age_days_centered, y=predict(quantile_lme, level=0, newdata=newdat[[i]]), size="Population")) +
scale_size_manual(name="Predictions", values=c("Subjects"=0.5, "Population"=3)) +
ggtitle((paste0("Predicted values for ",diag,"\nt-value:",round(summary(quantile_lme)$tTable[2,4],3)," p:",round(summary(quantile_lme)$tTable[2,5],3)," dof:",summary(quantile_lme)$tTable[2,3]))) +
theme_minimal() + facet_grid(~sex) +
theme(plot.title=element_text(hjust=0.5), legend.position = "bottom")

figlist[[i]] <- p

#ggsave(filename = paste0('./Figures/Figure3/Figure3A',i,'.pdf'),p, height = 4, width = 5)

}`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions