Plot 2 dataframes in one graph and create 2 legends

35 Views Asked by At

I have 2 dataframes which share column names (context, category, distance, what, where, mean, weight). The format here:

context category distance what    where       mean    weight
CG  missing     -100 mean upstream 0.59447911 0.3658334
CHH  missing     -100 mean upstream 0.11601219 0.3370685
CHG  missing     -100 mean upstream 0.40141491 0.3498439
CG  covered     -100 mean upstream 0.49565179 0.6341666
CHH  covered     -100 mean upstream 0.09904151 0.6629315
CHG  covered     -100 mean upstream 0.37704723 0.6501561

I want to plot 2 dataframes in one plot with some requirements below:

  • there will be 3 lines corresponding to 3 contexts (CHH, CHG, CG).
  • the line types will be 2 corresponding to 2 dataframes ('solid' for cambium and 'dotted' for leaf).
  • there will be 2 legends corresponding to the 2 requirements above.

I successfully plotted it, but I need to merge the 2 dataframes to the new one called rc_meth_cambium_leaf as the following before plotting:

context category distance what    where       mean    weight  sample
CG  missing     -100 mean upstream 0.59447911 0.3658334 cambium
CHH  missing     -100 mean upstream 0.11601219 0.3370685 cambium
CHG  missing     -100 mean upstream 0.40141491 0.3498439 cambium
CG  covered     -100 mean upstream 0.49565179 0.6341666 leaf
CHH  covered     -100 mean upstream 0.09904151 0.6629315 leaf
CHG  covered     -100 mean upstream 0.37704723 0.6501561 leaf

the working code is:

range <- 2000
breaks <- c(c(-1, -0.5, 0, 0.5, 1, 1.5, 2) * range)
labels <- c(-range, -range/2, '0%', '50%', '100%', range/2, range)
ggplot(rc_meth_cambium_leaf, aes_string(col = 'context')) + 
    geom_line(aes_string(x='distance', y='mean', linetype = 'sample')) +
    scale_x_continuous(breaks=breaks, labels=labels) + 
    scale_y_continuous(limits=c(0,1)) + 
    xlab('Distance from annotation') + 
    ylab('Mean recalibrated\nmethylation level') + 
    facet_grid(.~category)

The plot is: enter image description here

The merged dataset is: https://drive.google.com/file/d/1Tj2iFDi4d7cGVul-7WVObWUWZNetA7R_/view?usp=share_link

But I want to do the same thing without megering dataframe. However, I couldn't add the 2nd legend to the plot (the code just created the 'context' legend).

Here is the code and plot:

ggplot(cambium) +
    geom_line(aes_string(x='distance', y='mean', col='context'), linetype = "solid") +
    geom_line(data = leaf, aes_string(x='distance', y='mean', col='context'), linetype = "dotted") +
    scale_x_continuous(breaks=breaks, labels=labels) + scale_y_continuous(limits=c(0,1)) +
    xlab('Distance from annotation') +
    ylab('Mean methylation\nlevel') +
    facet_grid(.~category)

enter image description here

My question is: can I do the same without merging the 2 dataframes?

I appreciate your help.

0

There are 0 best solutions below