English 中文(简体)
根据Y号拦截线的不同颜色
原标题:geom_smooth line different color based on Y intercept line

我的数据如下。 两栏、序号(SL)和表述价值(log)

> df

SL  log
1   1.5
2   -2.5
3   1.0
4   2.5
5   -1.

> ggplot(df, aes(x = SL, y = log)) +
  geom_point(size = 0.5, alpha = 0.6, shape = 19, color = "gray") +
  geom_smooth(method = "loess", se = FALSE, linewidth = 0.5, span = 0.09) +
  geom_hline(yintercept = 0, color = "black", lwd = 0.5)

“entergraph

然而,如果位于Y=0拦截线以下的Y=0拦截线和绿色线之上,我想要填满地-洋休息线,装满红色彩色。 例数如下。

“entergraph

我如何能够这样做?

问题回答

感谢各位的答复。 遵循守则是完美的:

smoothed_values <- predict(loess(log ~ SL, data = df, span = 0.09)) 
fill_color <- ifelse(smoothed_values >= 0, "red", "green")

plot <- ggplot(df, aes(x = SL, y = log)) +
  geom_point(size = 0.5, alpha = 0.6, shape = 19, color = "gray") +
  ggbraid::geom_braid(aes(SL, ymin = 0, ymax = smoothed_values, fill = fill_color), 
                      alpha = 0.5, lwd = 0.5, color = "gray3") +
  geom_hline(yintercept = 0, lwd = 0.25, color = "black") +
  labs(x = "Gene Order", y = "logFC") +
  scale_fill_identity(name = "Gene Expression", 
                      labels = c("Down", "Up"), guide = "legend", 
                      breaks = c("green", "red"), limits = c("green", "red")) +
  theme_minimal() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.line = element_line(colour = "black")) +
  scale_y_continuous(breaks = seq(-5, 5, by = 0.5))

“entergraph

I don t think there s a super simple answer, since you first need to extract the loess line to use it with geom_area (which can t vary in fill) or geom_ribbon (which won t automatically separate regions of the same sign).

我愿使用<代码>ggbraid。 一旦我们抽取了休息线,它将形成一个单独的填充区域的冰洁污染。

根据一些假数据:

df <- data.frame(x = 1:100, 
                 y = sin(seq(0,8, length.out = 100)) + sin(1:100))

我们可以使用

p <- ggplot(df, aes(x, y)) +
  geom_point() +
  geom_smooth()
df2 <- ggplot_build(p)[[1]][[2]][,c("x","y")]

然后,我们就有一个小小小小小小小 problem问题,涉及干涉,详情如下:herehere。 一种简单的解决办法是使用<代码>ggbraid的包裹,其中指明了准确的过境点,并对填充区进行了干净的区分。

# using ggbraid from remotes::install_github("nsgrantham/ggbraid")
ggplot(df, aes(x, y)) +
  ggbraid::stat_braid(aes(x, ymin = 0, ymax = y, fill = y < 0),
                      data = df2) +
  geom_point() +
  geom_line(data = df2) +
  geom_hline(yintercept = 0) +
  scale_fill_manual(values = c("red", "green"))

“enterography

这里的做法是将<代码>信号(y)改动的各行之间的数值加以推断,然后为<代码>stat_smooth数据设定两个组,一个为正值数据,一个为负值,最后用新数据重新计算。

第一,我们需要用平稳数据绘制一块地块。

library(ggplot2)
library(data.table)
# library(tidyr) ## we only need tidyr::fill
## example dataset
set.seed(123)
df.ex <- data.frame(s = 1:600, l = round(rnorm(600, sd = 2), 1))

## creating the first plot with stat_smooth; same fill color for + & -
ggplot(df.ex, aes(x = s, y = l)) +
  geom_point(size = 0.5, alpha = 0.6, shape = 19, color = "gray") +
  geom_hline(yintercept = 0, color = "black", lwd = 0.5) +
  stat_smooth(method = "loess", geom = "area", fill = "pink",
              se = FALSE, linewidth = 0.5, span = 0.09, 
              color = "blue",  alpha = 0.8) -> p; p

></p>
<p>然后,我们将从<代码>ggplot2</code>的物体中提取“加密数据”,并将找到<代码>x</code>坐标<code>geom_smooth</code>。 从正面的<条码>y</code>到负或反面(即<code>y=0</code>)。</p>
<pre class=## ggplot build to extract the smooth data q <- ggplot_build(p) #> `geom_smooth()` using formula = y ~ x smdat <- copy(q[[1]][[3]]) setDT(smdat) ## set the fill colors and group for negative and positive values smdat[ , group := ifelse(y > 0 , 1, 2)][, fill := ifelse(y < 0 , "green", "red")] ## interpolation; taken from https://stackoverflow.com/a/27137211/6461462 smdat_grp <- smdat[ , { ix = .I[c(FALSE, abs(diff(sign(smdat$y))) == 2)] if(length(ix)){ pred_x = sapply(ix, function(i) approx(x = y[c(i-1, i)], y = x[c(i-1, i)], xout = 0)$y) rbindlist(.(.SD, data.table(x = pred_x, y = 0, group = 1, ymax = 0), data.table(x = pred_x, y = 0, group = 2, ymax = 0)), fill = TRUE)} else .SD}][order(x)] ## filling the NA values in the remaining columns lapply(split(smdat_grp, smdat_grp$group), (dat) tidyr::fill(dat, everything(), .direction = "downup")) |> rbindlist() |> as.data.frame() -> q[[1]][[3]] ## plot the modified ggplot pq <- ggplot_gtable(q) plot(pq)

></p>
<p>如你所知,使用<代码>ggbraid:geom_braid</code>或<code>ggbraid:stat_braid</code>,虽然非常接近,但给我们带来与什么略有不同的结果;通过<编码> stat_smooth</code>/<code>/geom_smooth</code>绘制。</p>
<pre class=smoothed_values <- predict(loess(l ~ s, data = df.ex, span = 0.09)) fill_color <- ifelse(smoothed_values >= 0, "red", "green") ggplot(df.ex, aes(x = s, y = l)) + geom_point(size = 0.5, alpha = 0.6, shape = 19, color = "gray") + ggbraid::geom_braid(aes(s, ymin = 0, ymax = smoothed_values, fill = fill_color), alpha = 0.5, lwd = 0.5, color = "gray3") + geom_hline(yintercept = 0, lwd = 0.25, color = "black") + geom_smooth(method = "loess", se = FALSE, linewidth = 1, span = 0.09) + theme(legend.position = "none") + coord_cartesian(ylim = c(-1, 1)) ## zoom to see the difference #> `geom_braid()` using method = line #> `geom_smooth()` using formula = y ~ x

https://i.imgur.com/320N398.png” alt=">

Created on 2024-03-07 with reprex v2.0.2.





相关问题
How to plot fitted model over observed time series

This is a really really simple question to which I seem to be entirely unable to get a solution. I would like to do a scatter plot of an observed time series in R, and over this I want to plot the ...

REvolution for R

since the latest Ubuntu release (karmic koala), I noticed that the internal R package advertises on start-up the REvolution package. It seems to be a library collection for high-performance matrix ...

R - capturing elements of R output into text files

I am trying to run an analysis by invoking R through the command line as follows: R --no-save < SampleProgram.R > SampleProgram.opt For example, consider the simple R program below: mydata =...

R statistical package: wrapping GOFrame objects

I m trying to generate GOFrame objects to generate a gene ontology mapping in R for unsupported organisms (see http://www.bioconductor.org/packages/release/bioc/vignettes/GOstats/inst/doc/...

Changing the order of dodged bars in ggplot2 barplot

I have a dataframe df.all and I m plotting it in a bar plot with ggplot2 using the code below. I d like to make it so that the order of the dodged bars is flipped. That is, so that the bars labeled "...

Strange error when using sparse matrices and glmnet

I m getting a weird error when training a glmnet regression. invalid class "dgCMatrix" object: length(Dimnames[[2]]) must match Dim[2] It only happens occasionally, and perhaps only under larger ...

Generating non-duplicate combination pairs in R

Sorry for the non-descriptive title but I don t know whether there s a word for what I m trying to achieve. Let s assume that I have a list of names of different classes like c( 1 , 2 , 3 , 4 ) ...

Per panel smoothing in ggplot2

I m plotting a group of curves, using facet in ggplot2. I d like to have a smoother applied to plots where there are enough points to smooth, but not on plots with very few points. In particular I d ...

热门标签