繁体   English   中英

ggplot:避免在x轴上累加因子变量

[英]ggplot: Avoiding adding up factor variable in x-axis

我想避免在绘图中添加因子变量。 让我们考虑一下这些数据,

aa <- c(10, 12, 23)
bb <- c("a", "b", "a")
dataf <- data.frame(aa, bb)

library(ggplot2)
gplot <- ggplot(data=dataf, aes(x=bb, y=aa))+geom_bar(stat="identity")
gplot

此代码将生成以下条形图。

在此处输入图片说明

如您所见,有两个条形图,第一个条形图在y轴上的值为33(即10 + 23)。 我想避免这种增加。 这意味着,我想看到三个条形而不是两个。 我怎样才能做到这一点?

您可以创建一个新列,以标识每个组中的唯一值:

dataf$rn <- ave(dataf$aa, dataf$bb, FUN = seq_len)

然后绘制:

ggplot(data=dataf, aes(x=bb, y=aa, fill=factor(rn))) +
  geom_bar(stat="identity", position="dodge")

这使:

在此处输入图片说明

但是,由于这对于条形图的宽度并不能给出很好的显示,因此可以按以下方式扩展数据框:

# expand the dataframe such that all the combinations of 'bb' and 'rn' are present
dfnew <- merge(expand.grid(bb=unique(dataf$bb), rn=unique(dataf$rn)), dataf, by = c('bb','rn'), all.x = TRUE)
# replace the NA's with zero's (not necessary)
dfnew[is.na(dfnew$aa),'aa'] <- 0

然后再次绘图:

ggplot(data=dfnew, aes(x=bb, y=aa, fill=factor(rn))) +
  geom_bar(stat="identity", position="dodge")

这使:

在此处输入图片说明


为了回应您的评论,您可以执行以下操作:

dataf$rn2 <- 1:nrow(dataf)

ggplot(data=dataf, aes(x=factor(rn2), y=aa)) +
  geom_bar(stat="identity", position="dodge") +
  scale_x_discrete('', labels = dataf$bb)

这使:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM