처음 몇 가지 배경. ggplot2를 사용하여 폭포수를 만들려고합니다. 트릭을 수행하는 다음 함수를 작성했습니다. 그러나 geom_text 레이블에 사용자가 제공 한 서식 지정 기능을 제공하려고 할 때 작은 문제가 있습니다. 평가에서ggplot2의 geom_text에서 사용자가 제공 한 레이블에 오류가 나타나는 이유는 무엇입니까?
오류 (EXPR, envir, enclos) :
이
범인은이다 기능 "포맷"을 찾을 수 없습니다이 함수를 호출
plotIt<-function()
{
require(ggplot2)
require(scales)
# Define formatting functions
formatter<-function(x, ...) format(x, big.mark = ' ', trim = TRUE, scientific = FALSE, ...)
strwr<-function(x) gsub(" ", "\n", x)
# Build data frame to plot
mydf<-structure(list(Description = structure(1:6, .Label = LETTERS[1:6], class = "factor"),
change = c(0.86, 0.14, 0.08, -0.05, -0.03, 1.00),
id = 1:6,
end = c(0.86, 1.00, 1.08, 1.03, 1.00, 0.00),
start = c(0, 0.86, 1.00, 1.08, 1.03, 1.00),
type = structure(c(2L, 2L, 2L, 1L, 1L, 2L), .Label = c("Neg", "Pos"), class = "factor")),
.Names = c("Description", "change", "id", "end", "start", "type"),
row.names = LETTERS[1:6], class = "data.frame")
# Plot it
ggplot(mydf, aes(Description, fill = type)) +
geom_rect(aes(x = Description, xmin = id - 0.45, xmax = id + 0.45, ymin = end, ymax = start)) +
scale_y_continuous(labels = formatter) +
scale_x_discrete("", breaks = levels(mydf$Description), labels = strwr(levels(mydf$Description))) +
geom_text(aes(x = id, y = end, label = formatter(change)), vjust = 1, size = 3)
}
다음과 같은 오류 메시지를 생성합니다 최종 행 geom_text에 label = formatter (change) 코드가 있습니다. 레이블 = 쉼표 (바꾸기)로 바꾸면 모든 것이 잘 작동합니다. "쉼표"기능은 저울 패키지에서 제공됩니다. 그래서 짧은 :
geom_text(aes(x = id, y = end, label = comma(change)), vjust = 1, size = 3)
작동하지만
geom_text(aes(x = id, y = end, label = formatter(change)), vjust = 1, size = 3)
하지 않습니다.
출력은 다음과 같습니다
왜 내 자신의 포맷 기능을 허용 geom_text하지 않는 이유는 무엇입니까? 나는 그것이 단순한 것이라고 확신하지만 나는 그것을 볼 수 없다.
답장을 보내 주셔서 감사합니다. 실제로 그것은 문제를 해결했습니다. 이제 내가하는 일은 이유를 이해하는 것입니다. scale_y_continuous에서 레이블 = 포맷터는 어떻게 작동 하나 geom_text에서는 그렇지 않습니다. 에이스 전화 때문인가요? –
추가 설명 주셔서 감사합니다. 환경과도 관련이 있어야한다는 것을 알았지 만, geom_text가 필요하지만 environment = environment()없이 scale_y_continuous 코드가 작동하는 이유는 아직 모르겠다. 이상한 권리? –
맞아요,'aes()'ggplot은 전역 환경이나 정의 된 data.frame ('data =')를 찾습니다.다른 함수'strwr'도'aes()'밖에서도 작동하는 것을 볼 수 있습니다. – alexwhan