ggplot2::geom_text():如何显示所有因子水平,但抑制特定值,如“0”:
ggplot2::geom_text(): how to display all factor levels, but suppress specific values like '0':
这是为我的问题提供上下文的代码:
set.seed(1); tibble(x=factor(sample(LETTERS[1:7],7,replace = T),levels = LETTERS[1:7])) %>% group_by_all() %>% count(x,.drop = F) %>%
ggplot(mapping = aes(x=x,y=n))+geom_bar(stat="identity")+geom_text(
aes(label = n, y = n + 0.05),
position = position_dodge(1),
vjust = 0)
我希望变量 x 的所有级别都显示在 x 轴上 (LETTERS[1:7])。对于 n>0 的每个级别,我希望值显示在该级别的条形图上方。对于 n==0 的每个级别,我希望不显示值标签。目前,该图显示 'empty' 因子水平 c("C","F")的 0,我想抑制这些水平的“0”显示,但仍显示 "C",x 轴上的 "F"。
我希望有人能帮助我。
谢谢。
一个简单的ifelse()
就可以了。您可以输入任何您喜欢的文字,例如 ifelse( n>0, n , "No Data")
library( tidyr)
library( ggplot2)
library( dplyr )
set.seed(1); tibble(x=factor(sample(LETTERS[1:7],7,replace = T),levels = LETTERS[1:7])) %>% group_by_all() %>% count(x,.drop = F) %>%
ggplot(mapping = aes(x=x,y=n))+geom_bar(stat="identity")+
geom_text(
aes(label = ifelse( n>0, n , ""), y = n + 0.05),
position = position_dodge(1),
vjust = 0)
您将一个函数传递给 geom_test 中的数据参数,对于此示例,您可以对管道数据(称为 .x
)执行一个子集:
set.seed(1);
tibble(x=factor(sample(LETTERS[1:7],7,replace = T),levels = LETTERS[1:7])) %>% group_by_all() %>% count(x,.drop = F) %>%
ggplot(mapping = aes(x=x,y=n))+geom_bar(stat="identity")+
geom_text(data=~subset(.x,n>0),
aes(label = n, y = n + 0.05),
position = position_dodge(1),
vjust = 0)
这是为我的问题提供上下文的代码:
set.seed(1); tibble(x=factor(sample(LETTERS[1:7],7,replace = T),levels = LETTERS[1:7])) %>% group_by_all() %>% count(x,.drop = F) %>%
ggplot(mapping = aes(x=x,y=n))+geom_bar(stat="identity")+geom_text(
aes(label = n, y = n + 0.05),
position = position_dodge(1),
vjust = 0)
我希望变量 x 的所有级别都显示在 x 轴上 (LETTERS[1:7])。对于 n>0 的每个级别,我希望值显示在该级别的条形图上方。对于 n==0 的每个级别,我希望不显示值标签。目前,该图显示 'empty' 因子水平 c("C","F")的 0,我想抑制这些水平的“0”显示,但仍显示 "C",x 轴上的 "F"。
我希望有人能帮助我。
谢谢。
一个简单的ifelse()
就可以了。您可以输入任何您喜欢的文字,例如 ifelse( n>0, n , "No Data")
library( tidyr)
library( ggplot2)
library( dplyr )
set.seed(1); tibble(x=factor(sample(LETTERS[1:7],7,replace = T),levels = LETTERS[1:7])) %>% group_by_all() %>% count(x,.drop = F) %>%
ggplot(mapping = aes(x=x,y=n))+geom_bar(stat="identity")+
geom_text(
aes(label = ifelse( n>0, n , ""), y = n + 0.05),
position = position_dodge(1),
vjust = 0)
您将一个函数传递给 geom_test 中的数据参数,对于此示例,您可以对管道数据(称为 .x
)执行一个子集:
set.seed(1);
tibble(x=factor(sample(LETTERS[1:7],7,replace = T),levels = LETTERS[1:7])) %>% group_by_all() %>% count(x,.drop = F) %>%
ggplot(mapping = aes(x=x,y=n))+geom_bar(stat="identity")+
geom_text(data=~subset(.x,n>0),
aes(label = n, y = n + 0.05),
position = position_dodge(1),
vjust = 0)