使用 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/