如何解决无法将 scale_x_log10() 应用于我自己的几何图形:它错误地出现在绘图中
我正在尝试了解 ggproto
是如何编写我自己的几何图形的。
我写了 geom_myerrorbarh(类似于 geom_errorbarh,但只有 x
、y
、xwidth
参数)。下图显示一切都在线性范围内正常工作。但是,如果使用 log10 比例,则与 geom_errorbarh 不同。
我注意到在使用 scale_x_log10() 时,先转换 x=log10(x)
,然后转换 xmin=x-xwidth; xmax=x+xwidth
(请参阅 setup_data 参数)。但它应该是 xmin=log10(x-width); xmax=log10(x+xwidth)
。
如何解决这个问题?
library(grid)
library(ggplot2)
library(patchwork)
theme_set(theme_minimal())
GeomMyerrorbarh <- ggproto("GeomMyerrorbarh",Geom,required_aes = c("x","y","xwidth"),draw_key = draw_key_path,setup_data = function(data,params){
transform(data,xmin = x - xwidth,xmax = x + xwidth)
},draw_group = function(data,panel_scales,coord) {
## Transform the data first
coords <- coord$transform(data,panel_scales)
## Construct a grid grob
grid::segmentsGrob(
x0 = coords$xmin,x1 = coords$xmax,y0 = coords$y,y1 = coords$y,gp = gpar(lwd = coords$size,col = coords$colour,alpha = coords$alpha))
})
geom_myerrorbarh <- function(mapping = NULL,data = NULL,stat = "identity",position = "identity",na.rm = FALSE,show.legend = NA,inherit.aes = TRUE,...) {
ggplot2::layer(
geom = GeomMyerrorbarh,mapping = mapping,data = data,stat = stat,position = position,show.legend = show.legend,inherit.aes = inherit.aes,params = list(na.rm = na.rm,...)
)
}
df <- data.frame(x = c(1,2),y = c(1,xerr = c(0.1,0.2))
p1 <- ggplot(df,aes(x,y)) +
geom_point() +
geom_errorbarh(aes(xmin = x - xerr,xmax = x + xerr),height=0,size=4,alpha=0.2,color='red') +
geom_myerrorbarh(aes(xwidth = xerr)) +
labs(subtitle = 'Linear scale x')
p2 <- p1 +
scale_x_log10() +
labs(subtitle = 'Log10 scale x')
# Plot:
# Red transparent region - geom_errorbarh
# Black line - geom_myerrorbarh
p1 | p2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。