簡體   English   中英

在 R 中的 geom_bar 上的列頂部添加特定標簽

[英]Adding specific labels to a the top of columns on geom_bar in R

我有一個數據庫,其中包含我正在處理的示例。 我試圖讓代碼為每個變量(12 個變量)添加所有收入,然后在每列的頂部顯示一個數字的縮寫版本,因為它以數十億為單位,並且有兩個長。 問題似乎是我不能使用計數,因為我在美學上有 x 和 y,但是如果我剪掉一個,那么我就無法制作圖表。 這是我的代碼:

set.seed(180173)
renglones <- sample(1:nrow(Metro), size=300, replace = FALSE)
MuestraNE <- Metro[renglones, ]
View (MuestraNE)
summary(MuestraNE)

library(ggplot2)
library(reshape2)

ing = aggregate(.~ TIPO_INGRESO, FUN = sum, data=MuestraNE)

tot = colSums(ing[,3:14])
lblstot = c(tot[1]/100000000,tot[2]/100000000,tot[3]/100000000,tot[4]/100000000,
            tot[5]/100000000,tot[6]/100000000,tot[7]/100000000,tot[8]/100000000,
            tot[9]/100000000,tot[10]/100000000,tot[11]/100000000,tot[12]/100000000)
p <- as.numeric(lblstot)

gg <- melt(MuestraNE[ , 3:14])   
ggplot(gg, aes(x=variable, y=value)) + 
  geom_bar(fill = "orange", stat = "identity") + 
  ggtitle("Total por Línea de Metro")+
  geom_text(aes(y = p), vjust=-1, size = 3)+
  theme(axis.title = element_blank(), legend.position = "none",
        plot.title = element_text(hjust = 0.5, face = "bold"),
        axis.ticks = element_blank(), axis.text.y = element_blank(),
        axis.text.x = element_text(angle = 270, vjust = 0.3, hjust = -0.5,
                                   color = "black")) 

每當我嘗試使用 geom_text() 添加某種格式時,我總是會收到一條錯誤消息:

Error: Aesthetics must be either length 1 or the same as the data (3600): y
Run `rlang::last_error()` to see where the error occurred.

我已經嘗試了我在谷歌和這里可以找到的所有東西,但似乎沒有任何效果,如果你們能幫助我,我將不勝感激。 這是我的數據庫的鏈接libstot 部分是我試圖在每列頂部獲取的內容,即第一列頂部的 tot 1 /10000000,第二列頂部的 tot[2]/100000000 等等。

我認為您需要指定 in geom_text(x=..?, y=p) 也嘗試 ggrepel

如果可能的話,請在 csv 或其第一行中分享您的數據。

希望對您有所幫助

以下是一個通用示例。 {ggplot}適用於(長)數據幀。 一個好的策略是准備您的 dataframe 以包含標簽。 如果您僅為標簽提供向量,請確保標簽的長度與您定義的數據相匹配(檢查備選方案 2)

兩個附加點

  • 而不是geom_bar(... stat = "identity")您現在可以使用geom_col()
  • ggplot 中的美學可以被繼承,因此您可以將aes(x = variable, y = value)移動到ggplot()調用中。 我將其分開,因此您可以看到添加新的 dataframe(選項 2)允許您將文本作為“完全”單獨的圖層處理。 從長遠來看,這可能會派上用場/您將產生的其他問題/圖表。
df <- data.frame(
   variable = 1:12
  ,value = c(3,4,5,6,7,6,4,3,8,2,6,5)
)

# generate labels
lbl <- paste0(df$value, " B")
df <- df %>% mutate(label = lbl)

ggplot(data = df) +
  geom_col( aes(x = variable, y = value), fill = "orange") +          
  geom_text(aes(x = variable, y = value, label = label), vjust = 1)   # vjust offsets the label

在此處輸入圖像描述

選擇:

如果您選擇繼承美學映射以及“僅”提供 label 向量的內容。 代碼如下:

# we call data and set the x and y mappings
ggplot(data = df, aes(x=variable, y= value)) + 
  geom_col(fill = "orange") +
  #------------- annotation layer ---------------------
  # the anchor points of the labels are inherited from ggplot() call 
  geom_text(aes(label = lbl), vjust = 1)

暫無
暫無

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

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