YuLab-SMU / aplot

Decorate a plot with associated information
https://yulab-smu.top/aplot
92 stars 14 forks source link

xlim2 fails to align two figures #1

Open fionarhuang opened 4 years ago

fionarhuang commented 4 years ago

Hi Y叔,

It seems that xlim2 fail to align two figures that use position

library(tidyr)
library(dplyr)
library(ggplot2)
library(ggtree)
library(aplot)
library(patchwork)

# data to plot heatmap

set.seed(2019-11-07)
d <- matrix(rnorm(25), ncol=5)
rownames(d) <- paste0('g', 1:5)
colnames(d) <- paste0('t', 1:5)
d <- data.frame(d)
d$gene <- rownames(d)
dd <- gather(d, 1:5, key="condition", value='expr')

fig_heat <- ggplot() +
    geom_tile(data = dd, aes(condition, gene, fill=expr),
              position = position_nudge(x = -1)) +
    scale_fill_viridis_c() +
    scale_y_discrete(position="right") +
    theme_minimal() +
    xlab(NULL) + ylab(NULL)

##  points
df_point <- data.frame(condition = paste0("t", 1:5),
                       value = 2:6)
fig_point <- ggplot() +
    geom_point(data = df_point,
               aes(condition, value, size = value,
                   color = condition),
              position = position_nudge(x = -1)) +
    theme_minimal() +
    xlab(NULL) + ylab(NULL)

# align two figures
fig_point + xlim2(fig_heat) + fig_heat + plot_layout(ncol = 1)
fig_heat %>%
    insert_top(fig_point, height = 0.3)

align

The two figures have the same range

> layer_scales(fig_heat)$x$range
<ggproto object: Class RangeDiscrete, Range, gg>
    range: t1 t2 t3 t4 t5
    reset: function
    train: function
    super:  <ggproto object: Class RangeDiscrete, Range, gg>
> layer_scales(fig_point)$x$range
<ggproto object: Class RangeDiscrete, Range, gg>
    range: t1 t2 t3 t4 t5
    reset: function
    train: function
    super:  <ggproto object: Class RangeDiscrete, Range, gg>

The issue might be due to below, and I am not sure how to overwrite this...

> layer_scales(fig_point)$x$range_c
<ggproto object: Class RangeContinuous, Range, gg>
    range: 0 4
    reset: function
    train: function
    super:  <ggproto object: Class RangeContinuous, Range, gg>
> layer_scales(fig_heat)$x$range_c
<ggproto object: Class RangeContinuous, Range, gg>
    range: -0.5 4.5
    reset: function
    train: function
    super:  <ggproto object: Class RangeContinuous, Range, gg>