English 中文(简体)
图2
原标题:ggplot2 geom_point with binned x-axis for binary data
  • 时间:2012-04-09 10:33:35
  •  标签:
  • r
  • ggplot2

我正试图为双倍数据制造一个双倍化X-轴射线。 当我使用<代码>geom_point与双向和双向使用时,该地块则无必要(见图1)。 如图2所示,我想根据轴心的数值对数据进行二读,然后用<代码>geom_point在每两条内对冲积x和vg y进行绘图。 (将每一双 bin的肥料数量与点的大小挂钩)。 我可以通过综合数据来做到这一点,但我想知道,批量是否能够直接做到这一点。 我在<代码>stat_bindot上就座。 等等,但无法找到解决办法。 任何想法? 以下是一些法典。

感谢!

# simulate data
n=1000
y=rbinom(n,1,0.5)
x=runif(n)
data=data.frame(x,y)

# figure 1 - geom_point with binary data, pretty useless!
ggplot(data,aes(x=x,y=y)) + geom_point() + ylim(0,1)

# let s create an aggregated dataset with bins
bin=cut(data$x,seq(0,1,0.05))
# I am sure the aggregation can be done in a better way...
data.bin=aggregate(data,list(bin),function(x) { return(c(mean(x),length(x)))})

# figure 2 - geom_point with binned x-axis, much nicer!
ggplot(data.bin,aes(x=x[,1],y=y[,1],size=x[,2])) + geom_point() + ylim(0,1)

Figures 1 and2:

最佳回答

如@Kohske所说,在<代码>ggplot2中,没有直接的方法;必须先对数据进行分类,然后通过<编码>ggplot。 你的做法可行,但我会使用<代码> plyr 包裹而不是aggregate稍作改动。

library("plyr")
data$bin <- cut(data$x,seq(0,1,0.05))
data.bin <- ddply(data, "bin", function(DF) {
  data.frame(mean=numcolwise(mean)(DF), length=numcolwise(length)(DF))
})
ggplot(data.bin,aes(x=mean.x,y=mean.y,size=length.x)) + geom_point() + 
  ylim(0,1)

“entergraph

The advantage, in my opinion, is that you get a simple data frame with better names this way, rather than a data frame where some columns are matrices. But that is probably a matter of personal style than correctness.

问题回答

为此,我撰写了一份新的《章程》。

It takes nbins, bin_var, bin_fun and summary_fun as arguments, with defaults for all four.

  • The default for nbins depends on the number of data points.
  • The default for bin_var is "x". You can also set it to "y". This specifies the variable that is fed to bin_fun.
  • bin_fun is the binning function. By default, it s seq_cut which I wrote for the purpose. You can also write your own binning function. It just has to take data and nbins as arguments.
  • summary_fun is the summary function that is used to aggregate the bins. By default, it s mean. You can also specify aggregating functions for x and y separately with fun.x and fun.y.
  • If you use a geom which takes ymin and ymax as aesthetics, you can also specify fun.ymin and fun.ymax.

请注意,如果你具体说明aes(组 = 您的宾),bin_fun就被忽视,而是使用组别变量。 说明还将产生一个可检索到.count.的变量。

在你看来,你也这样做:

p <- ggplot(data, aes(x, y)) +
  geom_point(aes(size = ..count..), stat = "binner") +
  ylim(0, 1)

在本案中并不十分有用(尽管这表明了同质,差异大约为0.25,相当于伯尔尼(0.5)的假设,但仅举一例:

p + geom_linerange(stat = "binner",
                   fun.ymin = function(y) mean(y) - var(y) / 2,
                   fun.ymax = function(y) mean(y) + var(y) / 2)

“geom_point

该法典:

library(proto)

stat_binner <- function (mapping = NULL, data = NULL, geom = "point", position = "identity", ...) {
  StatBinner$new(mapping = mapping, data = data, geom = geom, position = position, ...)
}

StatBinner <- proto(ggplot2:::Stat, {
  objname <- "binner"

  default_geom <- function(.) GeomPoint
  required_aes <- c("x", "y")

  calculate_groups <- function(., data, scales, bin_var = "x", nbins = NULL, bin_fun = seq_cut, summary_fun = mean,
                       fun.data = NULL, fun.y = NULL, fun.ymax = NULL, fun.ymin = NULL,
                       fun.x = NULL, fun.xmax = NULL, fun.xmin = NULL, na.rm = FALSE, ...) {
    data <- remove_missing(data, na.rm, c("x", "y"), name = "stat_binner")

    # Same rules as binnedplot in arm package
    n <- nrow(data)
    if (is.null(nbins)) {
      nbins <- if (n >= 100) floor(sqrt(n))
              else if (n > 10 & n < 100) 10
              else floor(n/2)
    }

    if (length(unique(data$group)) == 1) {
      data$group <- bin_fun(data[[bin_var]], nbins)
    }

    if (!missing(fun.data)) {
      # User supplied function that takes complete data frame as input
      fun.data <- match.fun(fun.data)
      fun <- function(df, ...) {
        fun.data(df$y, ...)
      }
    } else {
      if (!is.null(summary_fun)) {
        if (!is.null(fun.x)) message("fun.x overriden by summary_fun")
        if (!is.null(fun.y)) message("fun.y overriden by summary_fun")
        fun.x <- fun.y <- summary_fun
      }

      # User supplied individual vector functions
      fs_x <- compact(list(xmin = fun.x, x = fun.x, xmax = fun.xmax))
      fs_y <- compact(list(ymin = fun.ymin, y = fun.y, ymax = fun.ymax))

      fun <- function(df, ...) {
        res_x <- llply(fs_x, function(f) do.call(f, list(df$x, ...)))
        res_y <- llply(fs_y, function(f) do.call(f, list(df$y, ...)))
        names(res_y) <- names(fs_y)
        names(res_x) <- names(fs_x)
        as.data.frame(c(res_y, res_x))
      }
    }
    summarise_by_x_and_y(data, fun, ...)
  }


})

summarise_by_x_and_y <- function(data, summary, ...) {
  summary <- ddply(data, "group", summary, ...)
  count <- ddply(data, "group", summarize, count = length(y))

  unique <- ddply(data, "group", ggplot2:::uniquecols)
  unique$y <- NULL
  unique$x <- NULL

  res <- merge(merge(summary, unique, by = "group"), count, by = "group")

  # Necessary for, eg, colour aesthetics
  other_cols <- setdiff(names(data), c(names(summary), names(unique)))
  if (length(other_cols) > 0) {
    other <- ddply(data[, c(other_cols, "group")], "group", numcolwise(mean))
    res <- merge(res, other, by = "group")
  }

  res
}


seq_cut <- function(x, nbins) {
  bins <- seq(min(x), max(x), length.out = nbins)
  findInterval(x, bins, rightmost.closed = TRUE)
}




相关问题
How to plot fitted model over observed time series

This is a really really simple question to which I seem to be entirely unable to get a solution. I would like to do a scatter plot of an observed time series in R, and over this I want to plot the ...

REvolution for R

since the latest Ubuntu release (karmic koala), I noticed that the internal R package advertises on start-up the REvolution package. It seems to be a library collection for high-performance matrix ...

R - capturing elements of R output into text files

I am trying to run an analysis by invoking R through the command line as follows: R --no-save < SampleProgram.R > SampleProgram.opt For example, consider the simple R program below: mydata =...

R statistical package: wrapping GOFrame objects

I m trying to generate GOFrame objects to generate a gene ontology mapping in R for unsupported organisms (see http://www.bioconductor.org/packages/release/bioc/vignettes/GOstats/inst/doc/...

Changing the order of dodged bars in ggplot2 barplot

I have a dataframe df.all and I m plotting it in a bar plot with ggplot2 using the code below. I d like to make it so that the order of the dodged bars is flipped. That is, so that the bars labeled "...

Strange error when using sparse matrices and glmnet

I m getting a weird error when training a glmnet regression. invalid class "dgCMatrix" object: length(Dimnames[[2]]) must match Dim[2] It only happens occasionally, and perhaps only under larger ...

Generating non-duplicate combination pairs in R

Sorry for the non-descriptive title but I don t know whether there s a word for what I m trying to achieve. Let s assume that I have a list of names of different classes like c( 1 , 2 , 3 , 4 ) ...

Per panel smoothing in ggplot2

I m plotting a group of curves, using facet in ggplot2. I d like to have a smoother applied to plots where there are enough points to smooth, but not on plots with very few points. In particular I d ...

热门标签