繁体   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