histogram获得的y比例的优先级

histogram获得的y比例的优先级

本文介绍了如何确定从geom_histogram获得的y比例的优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在直方图上画一条垂直线,其中数据的中值在刻面之后.我想用stat_summary做到这一点,如下所示.这种方法的问题是y轴不在正确的比例上

I would like to draw a vertical line on a histogram where the median of my data are after faceting. I'd like to do this with stat_summary as shown below. The problem with this approach is that the y axis is not on the right scale

我认为这是因为我打电话给ggplot(aes(x=data, y=data)).对于直方图来说似乎有些奇怪,但是我这样做的原因是因为stat_summary需要y美观.有没有一种方法可以用stat_summary绘制中位数,但保持我调用geom_histogram时得到的标度?我可以添加ylim,但是这种方法的问题是我可能不知道正确的上限是可以看到的新数据的先验.

I think this is because I call ggplot(aes(x=data, y=data)). Seems a bit strange to do for a histogram, but the reason I do this is because stat_summary requires a y aesthetic. Is there a way I could plot the medians with stat_summary but keep the scale I get from when I call geom_histogram? I could add a ylim but the problem with that approach is that I may not know what the right upper limit is a priori for new data I might see.

以下是生成我的示例的代表.

Below is a reprex to generate my example.

library(tidyverse)
#> Warning: package 'tibble' was built under R version 3.6.2

d = tribble(
  ~groupvar, ~data,
  'a', rlnorm(10,2, 0.5),
  'b', rlnorm(10,2, 0.5),
  'c', rlnorm(10,5, 0.5)
) %>% unnest(c(data))



d %>%
  ggplot(aes(x = data, y = data, group = groupvar))+
  geom_histogram(aes(y = ..count..))+
  facet_grid(~groupvar)+
  stat_summary(aes(x=0, xintercept=stat(y)), fun = median, geom = 'vline')
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

推荐答案

您只能在stat_summary层中删除y = ..count..并映射y:

You can delete y = ..count.. and map y only in the stat_summary layer:

d %>%
  ggplot(aes(x = data, group = groupvar))+
  geom_histogram() +
  facet_grid(~groupvar) +
  stat_summary(aes(y = 0, xintercept=stat(x)), fun = median, geom = 'vline')

我还(a)在stat_summary层中删除了x = 0,并且(b)将stat(y)更改为stat(x)(因为您正在绘制垂直线,所以将其作为x的摘要是有意义的值).

I also (a) removed the x = 0 in the stat_summary layer and (b) changed stat(y) to stat(x) (since you're plotting a vertical line, makes sense for it to be a summary of the x values).

这篇关于如何确定从geom_histogram获得的y比例的优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 12:41