在geom_label中删除ifelse上的“False”条件缩放::美元标签

时间:2018-06-05 19:22:40

标签: r ggplot2 label

仅在值为负时尝试建立单独的条形数据标签。我能够为包含简单整数的变量做得很好,但是对于需要用千位分隔符格式化为美元的变量,我似乎无法摆脱“NA”标签。

DolSumPlot <- ggplot(data = DolSums, aes(x = Group.1, fill = Group.2)) + 
  geom_bar(aes(weight = x), position = position_stack(reverse = TRUE)) + 
  coord_flip() + 
  labs(title = "Dollars Billed by Technician and Shop, Between 02/01/2018 and 05/31/2018", 
       y = "Dollars Billed", x = "Technician", fill = "Shop") + 
  scale_y_continuous(limits= c(NA,NA),
                     labels = scales::dollar,
                     breaks = seq(0, 50000 + 10000, 5000*2),
                     minor_breaks = seq(0,50000 + 10000, by = 5000)) +
  scale_fill_brewer(palette = "Set1") + 
  geom_label(aes(label=scales::dollar(ifelse(DolSums$x < 0, DolSums$x,NA)), 
                 y = DolSums$x), 
             show.legend = FALSE, size = 2.6, colour = "white", fontface = "bold")

数据:

DolSums = structure(list(Group.1 = c((names)), Group.2 = structure(c(4L, 4L, 4L, 4L, 4L, 4L, 
4L, 4L, 4L, 4L, 4L, 4L, 3L, 3L, 3L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 
5L, 5L, 5L, 5L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Radio", 
"Video", "Engineering", "800Mhz", "PSSRP", "Other"), class = "factor"), 
    x = c(4646, 16008.5, 48793.1, 4040, 14468.25, 13332, 1565.5, 
    6060, 6549.85, 2929, 4444, 3257.25, 5904, 2029.5, 3321, 6767, 
    8105.25, 8105.25, 8130.5, 3131, 5075.25, 3383.5, 4418.75, 
    23381.5, 1363.5, -2323, 29133.45, 2550.25, 505, 26042.85, 
    35203.55, 35940.85, 1641.25, 45066.2, 37541.7, 606, 45439.9
    )), .Names = c("Group.1", "Group.2", "x"), row.names = c(NA, 
-37L), class = "data.frame")

1 个答案:

答案 0 :(得分:3)

您可以使用data中的geom_label参数并仅对具有负x的行进行子集来执行此操作。另请注意,由于您已经输入DolSums,因此无需编写DolSums$x。而是使用列名直接引用特定列:

library(ggplot2)

ggplot(data = DolSums, aes(x = Group.1, fill = Group.2)) + 
  geom_bar(aes(weight = x), position = position_stack(reverse = TRUE)) + 
  coord_flip() + 
  labs(title = "Dollars Billed by Technician and Shop, Between 02/01/2018 and 05/31/2018", 
       y = "Dollars Billed", x = "Technician", fill = "Shop") + 
  scale_y_continuous(limits= c(NA,NA),
                     labels = scales::dollar,
                     breaks = seq(0, 50000 + 10000, 5000*2),
                     minor_breaks = seq(0,50000 + 10000, by = 5000)) +
  scale_fill_brewer(palette = "Set1") + 
  geom_label(data = DolSums[DolSums$x < 0,], 
             aes(label=scales::dollar(x), 
                 y = x), 
             show.legend = FALSE, size = 2.6, colour = "white", fontface = "bold")