简体   繁体   English

在 R 中的 geom_bar 上的列顶部添加特定标签

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

I have a database with a sample im working on.我有一个数据库,其中包含我正在处理的示例。 Im trying to get the code to add all the earnings for each variable (12 variables) and then display on top of each column an abbreviated version of the number because it is in the billions and it is two long.我试图让代码为每个变量(12 个变量)添加所有收入,然后在每列的顶部显示一个数字的缩写版本,因为它以数十亿为单位,并且有两个长。 The problem seems to be that I can't use count because I have x and y in aesthetics, but if I cut one out then I can't make the graph.问题似乎是我不能使用计数,因为我在美学上有 x 和 y,但是如果我剪掉一个,那么我就无法制作图表。 This is my code:这是我的代码:

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")) 

whenever I try to add some kind of format with geom_text() I always get an error saying:每当我尝试使用 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.

I've tried everything I could find on google and in here but nothing seems to work, I's appreciate a lot if you guys could help me out.我已经尝试了我在谷歌和这里可以找到的所有东西,但似乎没有任何效果,如果你们能帮助我,我将不胜感激。 This is the link to my database The libstot part is what I'm trying to get on top of each column, ie tot 1 /10000000 on top of the first column, tot[2]/100000000 on top of the second column etcetera. 这是我的数据库的链接libstot 部分是我试图在每列顶部获取的内容,即第一列顶部的 tot 1 /10000000,第二列顶部的 tot[2]/100000000 等等。

I think you need to specify the in geom_text(x=..?, y=p) Also try ggrepel我认为您需要指定 in geom_text(x=..?, y=p) 也尝试 ggrepel

If its possible share your data in csv or the first rows of it.如果可能的话,请在 csv 或其第一行中分享您的数据。

Hope it is helpful希望对您有所帮助

The following is a generic example.以下是一个通用示例。 {ggplot} works well with (long) data frames. {ggplot}适用于(长)数据帧。 A good strategy is to prepare your dataframe to have also the labels included.一个好的策略是准备您的 dataframe 以包含标签。 If you provide a vector only for the labels, make sure that the length of the labels fit with the data you define (check alternative 2)如果您仅为标签提供向量,请确保标签的长度与您定义的数据相匹配(检查备选方案 2)

Two additional points两个附加点

  • instead of geom_bar(... stat = "identity") you can now use geom_col()而不是geom_bar(... stat = "identity")您现在可以使用geom_col()
  • aesthetics in ggplot can be inherited, thus you could move the aes(x = variable, y = value) into the ggplot() call. ggplot 中的美学可以被继承,因此您可以将aes(x = variable, y = value)移动到ggplot()调用中。 I keep it separate, so you can see that adding a new dataframe (option 2) allows you to handle the text as a "fully" separate layer.我将其分开,因此您可以看到添加新的 dataframe(选项 2)允许您将文本作为“完全”单独的图层处理。 This might come handy in the long run/other problems/graphs you will produce.从长远来看,这可能会派上用场/您将产生的其他问题/图表。
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

在此处输入图像描述

Alternative:选择:

If you opt for inheritence of the aesthetic mapping and what to provide a label vector "only".如果您选择继承美学映射以及“仅”提供 label 向量的内容。 The code would read as follows:代码如下:

# 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