覆盖条形图上的条形图 - 如何对齐列?

时间:2016-09-23 01:53:10

标签: r graphics

我有一个条形图,我用stripchart覆盖了一个散点图。

Barplot(data1means)
stripchart(data1, add=TRUE, vertical = TRUE)

但是,散点图上的点与条形图上的条形图不对齐,如下所示:

here

那么如何更改散点图的间距以使它们匹配?据我了解,stripchart没有像space这样的widthbarplot变量。

1 个答案:

答案 0 :(得分:2)

使用基本图形,您可以使用points功能在条形图顶部绘制点。我们从条形图本身得到条形的x位置。我还提供了一种替代方法,其中平均值用点标记而不是条形图绘制:

# Fake data
set.seed(1)
dat = data.frame(group=LETTERS[1:5], y=rnorm(25,20,2))

# Assign the barplot to x so that x will contain the bar positions.
x = barplot(tapply(dat$y, dat$group, FUN=mean), ylim=c(0,1.05*max(dat$y)), col=hcl(240,100, 70))
points(rep(x, table(dat$group)), dat$y[order(dat$group)], pch=21, bg="red")

plot(rep(1:length(unique(dat$group)), table(dat$group)), 
     dat$y[order(dat$group)], pch=21, bg="blue",
     ylim=c(0,1.05*max(dat$y)), xlim=c(0.5,5.5), xaxt="n")
points(1:length(unique(dat$group)), 
         tapply(dat$y, dat$group, FUN=mean), 
         pch="\U2013", cex=3, col="red")
axis(side=1, at=1:5, labels=LETTERS[1:5])

enter image description here

这是使用ggplot2的相同两个图的版本。

library(ggplot2)

ggplot(dat, aes(group, y)) +
  stat_summary(fun.y=mean, geom="bar", fill=hcl(240,100,50)) + 
  geom_point() +
  theme_minimal()

ggplot(dat, aes(group, y)) +
  geom_point() +
  stat_summary(fun.y=mean, geom="point", pch="\U2013", 
               size=8, colour="red") + 
  scale_y_continuous(limits=c(0, max(dat$y))) +
  theme_bw() 

enter image description here

相关问题