R,在 ggplot 图上叠加条形图作为比例

R, superimposing a barplot as a scale on a ggplot graph

我在 RStudio 工作并使用 ggplot2。我想创建一个条形图,它可以有效地充当 meters/second 的比例尺。然后我想创建一个 ggplot 图,这个条形图叠加在图上并且稍微透明。所以,我会有这样的东西:

   barplot(DF1,space=20,axes=FALSE,las=2,col=1,xlab="meters/second")

创建这个:

ggplot 是:

ggplot(DF2, aes(x=Time, y=N1_ave)) + geom_line() + ylim(-1,1) + ggtitle("0.07 MA Average")

创建:

合并后我想要的是这样的:

这可能吗?

如果没有看到您的数据,很难确定,但根据您的描述,这样怎么样:我们将创建一个 ggplot,但我们将使用一个数据框来绘制 N1_ave 使用 geom_line 和另一个使用 geom_segment 创建垂直线。这样,ggplot 负责所有缩放,我们不必担心两个不同地块之间的匹配比例。

关键是您必须在 barVals 中设置 x 值,以便在图表上的正确位置绘制垂直线。对于这个例子,我只是编造了它们,因为我不知道实际值应该是什么。

这是一个假数据的例子:

# This is the data series
set.seed(10)
dat = data.frame(x=seq(0,0.15,length.out=200), y=rnorm(200,0,0.2))

# These are the meters/second labels for the vertical lines
labels=c(0.27,0.29,0.31,0.33,0.36,0.4,0.44,0.5,
         0.57,0.67,0.8,1,1.34,2.01,4.02,Inf)

# These are the x-values for where the vertical lines will be plotted 
# (plus the labels created above)
barVals = data.frame(x=seq(0.005,0.145,length.out=length(labels)),
                     labels=labels)

ggplot(dat, aes(x,y)) +
  geom_segment(data=barVals, aes(x=x, xend=x), y=-0.8, yend=0.8, colour="grey70") +
  geom_text(data=barVals, aes(label=labels), y=-0.85, size=4, colour="grey50") +
  geom_line(aes(group=1)) + 
  scale_y_continuous(limits=c(-1,1)) +
  labs(x="Time", y="N1_ave") +
  annotate(geom="text", x=0.075, y=-0.95, label="meters/second", colour="grey50")