ggplot堆积条形图,y轴上有计数,但是百分比为标签

时间:2017-12-07 09:28:24

标签: r ggplot2 dplyr

我遇到的问题与曾经讨论过的问题有关。我在几个月前使用的这个例子R: ggplot stacked bar chart with counts on y axis but percentage as label产生了这种情节:

library(ggplot2)
library(dplyr)

df <- as.data.frame(matrix(nrow = 7, ncol= 3,
                   data = c("ID1", "ID2", "ID3", "ID4", "ID5", "ID6", "ID7",
                            "north", "north", "north", "north", "south", "south", "south",
                            "A", "B", "B", "C", "A", "A", "C"),
                  byrow = FALSE))




colnames(df) <- c("ID", "region", "species")


ggplot(df %>% count(region, species) %>%    # Group by region and species, then count number in each group
     mutate(pct=n/sum(n)),              # Calculate percent within each region
   aes(region, n, fill=species)) +
  geom_bar(stat="identity") +
  geom_text(aes(label=paste0(sprintf("%1.1f", pct*100),"%")), 
        position=position_stack(vjust=0.5))

一切都运作良好。但现在如果我运行相同的代码,我会得到这样的情节:

Myplot

有没有人有类似的问题?提前谢谢!

0 个答案:

没有答案