繁体   English   中英

使用ggplot2,如何创建直方图或条形图,其中最后一个条形是所有值大于某个数字的计数?

[英]Using ggplot2, how can I create a histogram or bar plot where the last bar is the count of all values greater than some number?

我想绘制我的数据的直方图以显示其分布,但是我有一些异常值与大多数值相比非常高,这些值<1.00。 而不是在最左边有一个或两个条形图然后直到图形的最右边,我想要一个除了异常值之外的所有内容的直方图,然后在标签的末尾添加一个条形图。在它下面是“> 100%”。 我可以使用gomplot2使用geom_bar()这样做:

 X <- c(rnorm(1000, mean = 0.5, sd = 0.2), 
   rnorm(10, mean = 10, sd = 0.5))
 Data <- data.frame(table(cut(X, breaks=c(seq(0,1, by=0.05), max(X)))))

 library(ggplot2)
 ggplot(Data, aes(x = Var1, y = Freq)) + geom_bar(stat = "identity") +
  scale_x_discrete(labels = paste0(c(seq(5,100, by = 5), ">100"), "%"))

直方图 问题在于,对于我需要的尺寸,标签最终重叠或需要以一定角度绘制以便于阅读。 我真的不需要标记所有的酒吧。 还有办法吗?

  • A)以不同于geom_bar()的方式绘制此图,这样我就不需要手动添加最后一个条或
  • B)只标注一些酒吧?

我会尽力回答B.

我不知道是否有一个参数可以让你做B)但你可以手动定义一个函数来为你做。 即:

library(ggplot2)
X <- c(rnorm(1000, mean = 0.5, sd = 0.2), 
       rnorm(10, mean = 10, sd = 0.5))
Data <- data.frame(table(cut(X, breaks=c(seq(0,1, by=0.05), max(X)))))

#the function will remove one label every n labels
remove_elem <- function(x,n) {
  for (i in (1:length(x))) {
    if (i %% n == 0) {x[i]<-''}
  }  
  return(x)  
}

#make inital labels outside ggplot (same way as before). 
labels <-paste0(c(seq(5,100, by = 5),'>100'),'%')

现在在ggplot函数中使用该函数:

ggplot(Data, aes(x = Var1, y = Freq)) + geom_bar(stat = "identity") +
  scale_x_discrete(labels = remove_elem(labels,2))

输出:

在此输入图像描述

我不知道这是不是你要找的东西,但它确实有用!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM