簡體   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