【问题标题】:R ggplot geom_text Aesthetic LengthR ggplot geom_text 审美长度
【发布时间】:2015-07-01 21:28:07
【问题描述】:

我正在处理一个非常大的数据集,其中包含一个虚拟变量和一个具有 14 个级别的因子变量——我已经发布了一个样本 here。我正在尝试使用以下代码制作堆叠比例条形图:

ggplot(data,aes(factor(data$factor),fill=data$dummy))+
geom_bar(position="fill")+
ylab("Proportion")+
theme(axis.title.y=element_text(angle=0))

效果很好,而且它几乎是我需要的情节。我只想添加小文本标签,报告每个因子水平的观察次数。我的直觉告诉我,这样的事情应该可以工作

Labels<-c("n=1853" , "n=392",  "n=181" ,  "n=80",   "n=69",   "n=32" ,  "n=10",    "n=6",    "n=4",    "n=5",    "n=3",    "n=3",    "n=2",    "n=1" ) 
ggplot(data,aes(factor(data$factor),fill=data$dummy))+
geom_bar(position="fill")+
geom_text(aes(label=Labels,y=.5))+
ylab("Proportion")+
theme(axis.title.y=element_text(angle=0))

但它会吐出一个空白图和错误 Aesthetics must either be length one, or the same length as the dataProblems:Labels

这对我来说真的没有意义,因为我知道一个事实,即我的因子水平的长度与我使用的标签数量相同。我一直在试图弄清楚如何才能得到它只是打印我需要的内容,而无需为this example 之类的观察次数创建值向量,但无论我尝试什么,我总是会遇到相同的美学错误。

【问题讨论】:

  • 不要在aes() 中使用$,如果你的情节变得更复杂(例如,方面),它会自找麻烦。 eipi 的回答很好地纠正了这一点。

标签: r graphics ggplot2 labels


【解决方案1】:

这个怎么样:

library(dplyr)

# Create a separate data frame of counts for the count labels
counts = data %>% group_by(factor) %>%
  summarise(n=n()) %>%
  mutate(dummy=NA)

counts$factor = factor(counts$factor, levels=0:10)

ggplot(data, aes(factor(factor), fill=factor(dummy))) +
  geom_bar(position="fill") +
  geom_text(data=counts, aes(label=n, x=factor, y=-0.03), size=4) +
  ylab("Proportion")+
  theme(axis.title.y=element_text(angle=0))

您的方法是正确的想法,但Labels 需要是一个数据框,而不是一个向量。 geom_text 需要使用 data 参数指定数据框的名称。然后,aes 中的label 参数告诉geom_text 使用哪一列作为标签。此外,即使geom_text 不使用dummy 列,它也必须在数据框中,否则会出现错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多