[英]Remove part of Y axis in ggplot
我正在尝试应用R/ggplot2: Collapse or remove segment of y-axis from scatter-plot以从我的绘图的 y 轴中删除 25 到 75 之间的值。 但是,当我对 plot 进行分组时,我没有得到想要的结果。
挤压部分 y 轴以使图清晰的最佳方法是什么。
library(scales)
squish_trans <- function(from, to, factor) {
trans <- function(x) {
if (any(is.na(x))) return(x)
# get indices for the relevant regions
isq <- x > from & x < to
ito <- x >= to
# apply transformation
x[isq] <- from + (x[isq] - from)/factor
x[ito] <- from + (to - from)/factor + (x[ito] - to)
return(x)
}
inv <- function(x) {
if (any(is.na(x))) return(x)
# get indices for the relevant regions
isq <- x > from & x < from + (to - from)/factor
ito <- x >= from + (to - from)/factor
# apply transformation
x[isq] <- from + (x[isq] - from) * factor
x[ito] <- to + (x[ito] - (from + (to - from)/factor))
return(x)
}
# return the transformation
return(trans_new("squished", trans, inv))
}
df <- data.frame(state = factor(c("CA", "NY", "TX", "CA", "NY", "CA", "NY", "TX")),
value = c(2,5,4,8,9,7,4,6),
rangeL = c(1,4,3,7,8,5,3,5),
rangeU = c(4,7,5,9,10,9,100,70),
grp = factor(c("x", "x","x","y", "y","z","z","z")))
df
df %>%
ggplot(aes(x=state, y= value, color = grp, group = grp)) +
geom_point(position=position_dodge(.7)) +
geom_errorbar(ymin = df$rangeL, ymax= df$rangeU, position=position_dodge(.7), width = 0.5) +
expand_limits(x = 0, y = 0) +
ylim(0, max(df$rangeU)) +
scale_y_continuous(trans = squish_trans(25, 75, 10),
breaks = c(0, 5, 10, 20, 25, 75, 100))
您的 trans function 没有任何问题。这是您使用geom_errorbar
的方式有问题。 由于某种原因,您没有将ymin
和ymax
美学映射到适当的列,而是将它们作为 geom 参数传递到aes
之外,因此在计算面板的正确范围时不会使用它们。
df %>%
ggplot(aes(x=state, y= value, color = grp, group = grp)) +
geom_point(position=position_dodge(.7)) +
geom_errorbar(aes(ymin = rangeL, ymax= rangeU),
position=position_dodge(.7), width = 0.5) +
scale_y_continuous(trans = squish_trans(25, 75, 10),
breaks = c(0, 5, 10, 20, 25, 75, 100))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.