[英]ggplot: Avoiding adding up factor variable in x-axis
您可以创建一个新列,以标识每个组中的唯一值:
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.