Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

r - double dots in a ggplot

I can not find the documentation for the double dots around density

set.seed(1234)
df <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))
print(head(df))
print(ggplot(df, aes(x=rating)) + 
    geom_histogram(aes(y=..density..),      # Histogram with density instead of count on y-axis
                   binwidth=.5,
                   colour="black", fill="white") +
    geom_density(alpha=.2, fill="#FF6666") +
    geom_vline(aes(xintercept=mean(rating, na.rm=T)),   # Ignore NA values for mean
               color="red", linetype="dashed", size=1))

Do you know what operator they represent ?

Edit

I know what it does when used in a geom, I would like to know what it is. For instance, the single dot operator is defined as

> .
function (..., .env = parent.frame()) 
{
    structure(as.list(match.call()[-1]), env = .env, class = "quoted")
}
<environment: namespace:plyr>

If I redefine density, then ..density.. has a different effect, so it seems XX -> ..XX.. is an operator. I would like to find how it is defined.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unlike many other languages, in R, the dot is perfectly valid in identifiers. In this case, ..count.. is an identifier. However, there is special code in ggplot2 to detect this pattern, and to strip the dots. It feels unlikely that real code would use identifiers formatted like that, and so this is a neat way to distinguish between defined and calculated aesthetics.

The relevant code is at the end of layer.r:

# Determine if aesthetic is calculated
is_calculated_aes <- function(aesthetics) {
  match <- "\.\.([a-zA-z._]+)\.\."
  stats <- rep(FALSE, length(aesthetics))
  grepl(match, sapply(aesthetics, deparse))
}

# Strip dots from expressions
strip_dots <- function(aesthetics) {
  match <- "\.\.([a-zA-z._]+)\.\."
  strings <- lapply(aesthetics, deparse)
  strings <- lapply(strings, gsub, pattern = match, replacement = "\1")
  lapply(strings, function(x) parse(text = x)[[1]]) 
}

It is used further up above in the map_statistic function. If a calculated aesthetic is present, another data frame (one that contains e.g. the count column) is used for the plot.

The single dot . is just another identifier, defined in the plyr package. As you can see, it is a function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...