簡體   English   中英

如何在barplot中更改ggplot2 x軸值?

[英]How to change ggplot2 x-axis values in barplot?

我想在R中制作一個條形圖,其中圖中的最后一個條形表示最后一個是頻率大於某個閾值的所有值的總和。 我想在最后一個欄上代表x值的相關信息。 例如:

library(ggplot2)

x <- c(1, 2, 3, 4, 5)
y <- c(4000, 3000, 2000, 1000, 500)

df <- data.frame(x, y)

names(df) <- c("Var1", "Freq")

theme_set(theme_classic())

g <- ggplot(df, aes(Var1, Freq))
g + geom_bar(stat = "identity", width = 0.5, fill = 'tomato2') + 
  xlab('Var1') +
  ylab('Freq') +
  theme(axis.text.x = element_text(angle = 0, 
                                   vjust = 0.6, 
                                   colour = "black"),
        axis.text.y = element_text(colour = "black"))

上面的代碼生成了一個類似於下面的圖表:

在此輸入圖像描述

但是在最后一個欄上,我希望x軸( x = 5 )的最后一個值顯示為>= 5

到目前為止,我已經嘗試使用scale_x_discrete 所以我在上面的代碼中添加了以下幾行:

n <- 5

# I'm not very creative with names.
.foo <- function(x, n) {
  if (x == n) {
    element <- paste('\u2265', toString(x), sep = ' ')
  } else {
    element <- toString(x)
  }
}

labels <- sapply(seq(n), .foo, n)

g + scale_x_discrete(breaks = sapply(seq(n), function(x) toString(x)),
                     labels = labels)

這段代碼按照我的意願格式化x軸,但它會覆蓋條形圖,留下一個空圖表:

在此輸入圖像描述

我怎樣才能做到這一點?

更改scale_x_continuous的標簽:

... + scale_x_continuous(labels=c("0", "1", "2", "3", "4", "\u2265 5"))

情節

一種方法是避免直接更改軸刻度標簽,但將Var1中的分類數據轉換為因子,然后使用forcats::fct_lump將該因子重新調整,使最終因子≥5

# Insert after df generated, before plot call
library(forcats)
df <- df %>% 
  mutate(Var1 = as_factor(Var1),
         Var1 = fct_lump_min(Var1, min = 501, w = Freq, other_level = "≥5"))

問題是,正如@ Z.Lin評論所指出的那樣,我在使用scale_x_discret之前將geom_bar(...)分配給ggplot對象。 這是解決方案:


library(ggplot2)
  ...
  labels <- sapply(seq(n), .foo, n)

  g <- ggplot(df, aes(Var1, Freq)) + 
         scale_x_discrete(breaks = sapply(seq(n), function(x) toString(x)),
                          labels = labels)

  g + geom_bar(stat = "identity", width = 0.5, fill = color) + 
  ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM