我在ggplot 2中创建了一些堆积条形图,并想知道如果它们小于定义的总数百分比(例如10%),我可以有条件地隐藏某些数据标签。
从下面的代码生成的图中可以看出,一些标签相对于条的厚度变得太大。所以我想隐藏那些低于定义的阈值。我怎样才能修改下面的ggplot代码来实现呢?谢谢!
library(ggplot2)
library(dplyr)
#Creating the dataset
my.data <- data.frame(dates = c("1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014"),
fruits=c("apple", "orange", "pear", "berries", "watermelon", "apple", "orange", "pear", "berries", "watermelon"),
count=c(20, 30, 40, 2, 2, 30, 40, 50, 1, 1))
#Creating a positon for the data labels
my.data <-
my.data %>%
group_by(dates) %>%
mutate(pos=cumsum(count)-0.5*count)
#Plotting the data
ggplot(data=my.data, aes(x=dates, y=count, fill=fruits))+
geom_bar(stat="identity")+
geom_text(aes(y=pos, label=count), size=4)
答案 0 :(得分:5)
您可以在geom_text
图层中对数据进行子集化。例如
ggplot(data=my.data, aes(x=dates, y=count, fill=fruits))+
geom_bar(stat="identity")+
geom_text(data=subset(my.data, count>10), aes(y=pos, label=count), size=4)