想用 ggplot 将折线图重叠在条形图上。 假设V1、V2是条形图的数据,V3应以线的形式呈现。 如何同时完成子集和不同的geom?
library(data.table)
library(ggplot2)
set.seed(100)
dat <- data.frame(Axis=letters[1:10],V1=1:10, V2=runif(10, 1,10), V3=10:1)
dat <-melt(data,id.var="Axis",measure.var=c("V1","V2","V3"))
会是这样吗?
ggplot(dat, aes(x=Axis)) +
geom_bar(stat="identity", aes(, y= value[------]))+ # V1, V2 for bars
geom_line(aes(y=value[-----)) # V3 for line
我尝试制作 V1、V2 的子集,并制作条形图,但无法将 V3 作为一条线插入图表上。
非常感谢
感谢@dash2,我稍微改变了他的代码,并使其看起来更清晰。
ggplot(dat, aes(x = Axis)) +
geom_col(aes(y = V1), fill = "darkred", alpha = .5, width=0.4) +
geom_col(aes(y = V2), fill = "blue", alpha = .5,
position = position_nudge(x = 0.4),width=0.4) +
geom_line(aes(y = V3, group = NA))
最佳答案
最简单,不熔化。
ggplot(data, aes(x = Axis)) +
geom_col(aes(y = V1), fill = "darkred", alpha = .5) +
geom_col(aes(y = V2), fill = "blue", alpha = .5,
position = position_nudge(x = 0.2)) +
geom_line(aes(y = V3, group = NA))
为品味增添美感。
group
参数是必要的。我认为离散刻度(如此处的 x 轴)会自动对它们的值进行分组,让您得到 1 组并且没有绘制任何线......一致,但不直观。
关于r - 使用 ggplot 同时重叠折线图和条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49590265/