向 ggplot 添加第二个 y 轴

时间:2021-01-04 08:50:30

标签: r ggplot2

我有以下数据集:

structure(list(Jahr = 2005:2019, Fahrrad = c(275208L, 296105L, 
308336L, 313363L, 326017L, 311756L, 302193L, 295702L, 268773L, 
268295L, 256726L, 248916L, 250242L, 233652L, 230464L), E.Bike = c(1792L, 
3181L, 5825L, 12600L, 23886L, 39247L, 49615L, 52941L, 49362L, 
57613L, 66332L, 75665L, 87987L, 111661L, 133032L), gesamt = c(277000L, 
299286L, 314161L, 325963L, 349903L, 351003L, 351808L, 348643L, 
318135L, 325908L, 323058L, 324581L, 338229L, 345313L, 363496L
)), class = "data.frame", row.names = c(NA, -15L))

我的目标是创建一个图表,在左侧 y 轴上显示不同自行车类型的绝对购买量。在右侧 y 轴 id 喜欢显示“E-Bike”购买与“Fahrrad”购买的比率以强调趋势(如果两者均等销售,则所需值为 100,如果电动自行车小于 100) .像这样:

desired output

这可能吗?我知道 ggplot 不允许使用第二个 y 轴。

这是生成下面绘图的代码(没有 MS 绘图编辑)

dfm <- melt(df, id="Jahr")

dfm$variable <- factor(dfm$variable, levels = c("gesamt", "Fahrrad", "E.Bike"))
dfm$variable <- revalue(dfm$variable, c("E.Bike"="E-Bike"))
dfm$value <- dfm$value/1000

ggplot(data=dfm) +
  geom_line(aes(x=dfm$Jahr, y=dfm$value, colour=dfm$variable),  lineend = "round", lwd=1.5)+
  scale_x_continuous(limits = c(2013,2019), breaks = c(2013, 2014, 2015,2016,  2017,2018,  2019))+
  scale_y_continuous(limits = c(0, 400))+
  labs(title = "Verkäufe in Tausend")+
  theme_minimal()+
  scale_colour_manual(name="Mode",
                      labels=c("Total", "Fahrrad","E-Bike"),
                      values = c( "#8c8c8c", "#256bc2","#7ea9de"),
                      guide="none")+
  geom_text(x = 2013.5, y = 350, label="Total" , hjust = "inward", size=3) + 
  geom_text(x = 2013.5, y = 290, label="Fahrrad" , hjust = "inward", size=3) + 
  geom_text(x = 2013.5, y = 80, label = "E-Bike", hjust = "inward", size=3)+
  theme(legend.title = element_blank(),
        axis.title.y=element_blank(),
        axis.title.x=element_blank(),
        panel.grid.minor.x=element_blank(),
        panel.grid.major.x=element_blank(),
        axis.text=element_text(size=8.5),
        plot.title = element_text(hjust = -0.06, size=9),
        plot.caption = element_text(hjust = -0.08, size=6,color="#BFBFBF"))

1 个答案:

答案 0 :(得分:1)

辅助轴在ggplot中的工作方式如下。在位置标度上,为次轴添加 sec.axis 参数,该轴是第一个轴的线性变换,在 trans 中指定。由于主轴和副轴都可以从 0 开始,这意味着一个简单的缩放因子就可以了。您需要手动转换输入数据并将反向转换指定为 trans 参数。下面的简化示例(假设 df 是您提供的数据):

library(ggplot2)
library(scales)

dfm <- reshape2::melt(df, id="Jahr")

# Scale factor for utilising whole y-axis range
scalef <- max(df$gesamt) / max(df$E.Bike / df$gesamt)

# Scale factor for using 0-100%
# scalef <- max(df$gesamt)

ggplot(dfm, aes(Jahr, value)) +
  geom_line(aes(colour = variable)) +
  geom_line(aes(y = E.Bike / gesamt * scalef),
            data = df, linetype = 2) +
  scale_y_continuous(
    labels = number_format(scale = 1e-3),
    sec.axis = sec_axis(trans = ~ .x / scalef,
                        labels = percent_format(),
                        name = "Percentage E-bike")
  )

reprex package (v0.3.0) 于 2021 年 1 月 4 日创建