如何制作带有第二个y轴的分组条形图(折线图)

时间:2019-05-16 11:13:56

标签: r ggplot2

我想制作一个条形图,显示每个年龄段的年代和认知年龄,并在右侧显示第二个y轴,以线图形式将差异表示为百分比(称为“ Delta”)。 希望你能帮助我。

我尝试了以下操作,但是我不知道如何将“ Delta”指定为第二个y轴。

dput(comparison_age)
structure(list(Mean = structure(1:7, .Label = c("20s", "30s", 
"40s", "50s", "60s", "70s", "80s"), class = "factor"), Chronologic = c(24.7, 
34, 45.2, 55.1, 64.8, 74.6, 81.5), Cognitive = c(27.2, 32.7, 
42.5, 49.1, 57, 68.4, 73.6), Delta = structure(c(7L, 4L, 5L, 
2L, 3L, 6L, 1L), .Label = c("-10%", "-11%", "-12%", "-4%", "-6%", 
"-8%", "10%"), class = "factor")), class = "data.frame", row.names = c(NA, 
-7L))
dput(comparison_age)
df <- data.frame(Mean, Chronologic, Cognitive, Delta)
barplot(comparison_age, x= "Mean", y="Chronologic", beside=T)

require(tidyr)
library(ggplot2)
df.long <- gather(df, variable, value, -Mean)
ggplot(data = df.long, aes(x = Mean, y = value, fill = variable)) +
  geom_col(position = position_dodge())

This is how it looks right now

1 个答案:

答案 0 :(得分:0)

出色的可复制代码!

我首先将您的df.long$value列转换为数值,因为要绘制连续的因子很困难。您可以通过将%替换为空字符串并转换为数字来实现。

df.long$value <- as.numeric(gsub("%", "", df.long$value))

然后,我们可以使用sec.axis中的scale_y_continuous()参数来绘制辅助轴。另外,我们需要使用几何中的data参数将要绘制为条形的内容与要绘制为线形的内容分开。此外,我在增量中加上了+20,并从辅助轴减去-20,以使其与第一个轴更接近,因为第二个轴只是第一个轴的变换。

ggplot(data = df.long, aes(x = Mean, y = value)) +
  geom_col(data = df.long[df.long$variable != "Delta" ,], position = position_dodge(),
           aes(fill = variable)) +
  geom_line(data = df.long[df.long$variable == "Delta",], 
            aes(group = 1, y = value + 20)) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~.- 20, name = "Delta"))

哪个给了我这个情节:

enter image description here

希望有帮助!