R 向ggplot添加第二个y轴

R 向ggplot添加第二个y轴,r,ggplot2,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, 4

我有以下数据集:

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轴上,我想显示“E-Bike”购买量与“Fahrrad”购买量的比率,以强调趋势(如果两者销售相同,则期望值为100,如果E-Bike小于100)。大概是这样的:

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

以下是生成以下绘图的代码(不带MS paint编辑)


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

库(ggplot2)
图书馆(比例尺)

dfm I通过采用这种方法成功地做到了这一点:
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"))