我正在尝试应用R/ggplot2:从散点图中折叠或删除 y 轴段,以从绘图的 y 轴中删除 25 到 75 之间的值。但是,当我对图进行分组时,我没有得到所需的结果。
挤压 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))
Run Code Online (Sandbox Code Playgroud)
你的 trans 功能没有任何问题。这是你使用的方式geom_errorbar有问题。由于出于某种原因,您没有将ymin和ymax美学映射到适当的列,而是将它们作为 外部的几何参数传递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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
303 次 |
| 最近记录: |