有条件地将数据标签隐藏在ggplot2图中 [英] Conditionally hiding data labels in ggplot2 graph

查看:336
本文介绍了有条件地将数据标签隐藏在ggplot2图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ggplot 2中创建了一些堆积的条形图,并想知道如果我们可以有条件地隐藏某些数据标签,如果它们小于总数的定义百分比,例如10%。

从下面的代码生成的图中可以看到,一些标签相对于条的粗细变得太大。所以我想隐藏那些比定义的阈值更低的值。我如何修改下面的ggplot代码来实现呢?

 库(ggplot2)
库(dplyr)

#创建数据集
my.data< - data.frame(dates = c(1/1/2014,1/1/2014,1/1/2014,1/1/2014, 2014年1月1日,2/1/2014,2/1/2014,2/1/2014,2/1/2014,2/1/2014),
fruits = c(apple,orange,pear,berries,西瓜,apple,orange,pear,berries,西瓜),
count = c(20,30,40,2,30,40,50,1,1))

#为数据标签创建位置
my.data < -
my.data%>%
group_by(日期)%>%
mutate(pos = cumsum(count)-0.5 * count)

#绘制数据
ggplot(data = my.data,aes(x = dates,y = count,fill = fruits))+
geom_bar(stat =identity)+
geom_text(aes(y = pos,label = count),size = 4)


解决方案

您可以在 geom_text 图层中对数据进行子集划分。例如

  ggplot(data = my.data,aes(x =日期,y = count,fill = fruits))+ 
geom_bar(stat =identity)+
geom_text(data = subset(my.data,count> 10),aes(y = pos,label = count),size = 4)


I am creating some stacked bar charts in ggplot 2, and wonder how I can conditionally hide certain data labels if they are smaller than a defined percentage of the total, e.g., 10%.

As you can see from the plot generated from the code below, some of the labels become too huge relative to the thickness of the bar. So I would like to hide those than less than the defined threshold. How can I modify the ggplot code below to achieve that? Thanks!

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)

解决方案

You can subset the data in the geom_text layer. For example

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)

这篇关于有条件地将数据标签隐藏在ggplot2图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆