r - R 和 ggplot 中有没有办法创建带有条件几何图形的facet_wrap 图?

标签 r ggplot2 facet-wrap

使用 R,我想创建一个 ggplot 分面图表,其中每个分面上包含一条零线(使用 geom_hline),其数据跨越零线,同时排除每个分面上仅具有正数或负数数据的零线。这是一个代表。

library(ggplot)
dfw <- data.frame(
  date=c(1,2,3,4,5,6),
  A=c(50,53,62,56,54,61),
  B=c(-3,-1,5,7,4,-2),
  C=c(6,4,5,2,3,-2)
)
dfl <- pivot_longer(dfw,2:4,names_to="nms",values_to="val")
# With no zero line: works fine
ggplot(dfl)+
  geom_line(aes(x=date,y=val))+
  facet_wrap(~nms,scales="free_y")
# With zero line for all facets: works fine
ggplot(dfl)+
  geom_hline(yintercept=0)+
  geom_line(aes(x=date,y=val))+
  facet_wrap(~nms,scales="free_y")
# With zero line, but only for facets with some data points greater than zero
# and other data points less than zero: Does not work
c0 <- ggplot(dfl)+
  geom_line(aes(x=date,y=val))
if (min(y)>0 | max(y)<0) { # Error: object 'y' not found
  c0 <- c0+geom_hline(yintercept=0) 
} 
c0 <- c0+facet_wrap(~nms,scales="free_y")

最佳答案

您可以在绘图之前计算每个面的 y 轴截距,如果数据包含 0 则设置为 0,否则设置为 NA:

library(ggplot2)
library(dplyr)

dfl <- dfl %>% 
  mutate(
    zline = ifelse(min(val) < 0 & max(val > 0), 0, NA),
    .by = nms    # `.by` argument added in dplyr v1.1.0
  )

ggplot(dfl) +
  geom_hline(aes(yintercept = zline), na.rm = TRUE) +
  geom_line(aes(x = date, y = val)) +
  facet_wrap(~nms, scales = "free_y")

关于r - R 和 ggplot 中有没有办法创建带有条件几何图形的facet_wrap 图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75340252/

相关文章:

r - 使用 R ggplot2 生成 LaTeX 风格散点图

r - ggplot position_dodge 带有多个误差线

r - 使用 ggplot2 自动绘制所有 data.table 列的最佳方法

r - Knitr 内联 block 选项(无评估)或仅呈现突出显示的代码

r - 使用 NA 按类别将平均列添加到数据框

r - ggplot2:将构面/带状文本分成两行

r - ggplot 方面的可用空间和比例

r - 如何在没有 NA 值的 data.frame 中选择行

r - 美学中的未知问题破坏了 Shiny 应用程序中的 ggplotly 绘图

r - 如何仅使用部分数值变量来对 geom_tile ggplot 中的图 block 进行排序