首页 > 解决方案 > 在 ggplot2 中使用双 y 轴将两个变量绘制为同一图表上的线

问题描述

我有一个简单的数据集,其中包含三列(Year、SALES 和 EATR)中的数据。所以我的意图是用双 y 轴放在同一张图上。

    DATA_TEST<-structure(list(Year = c("2007", "2008", "2009", "2010", "2011", 
                                       "2012", "2013", "2014", "2015", "2016", "2017"), SALES = c(82152, 
                                                                                                  90060, 84940.6666666667, 89028.6666666667, 100179.333333333, 
                                                                                                  101262.666666667, 125874, 127030, 140164.666666667, 144648, 151250
                                       ), EATR = c(10.6, 9, 7.9, 7.9, 7.9, 7.9, 7.9, 7.9, 7.9, 7.9, 
                                                   9.7)), row.names = c(NA, -11L), class = c("tbl_df", "tbl", "data.frame"
                                                   ))

#Code for ploting


library(ggplot2)
library(dplyr)

p <- ggplot(DATA_TEST, aes(x = Year))
p <- p + geom_line(aes(y = SALES),alpha=2)

p


p <- p + geom_line(aes(y = EATR))
p

#Now using the sec.axis argument

p <- ggplot(DATA_TEST, aes(x = Year))
p <- p + geom_line(aes(y = SALES, colour = "SALES"))

# adding the EATR
p <- p + geom_line(aes(y = EATR, colour = "EFFECTIVE RATE"))

# now adding the secondary axis, 
p <- p + scale_y_continuous(sec.axis = sec_axis(~.*5, name = "EFFECTIVE RATE"))

# modifying colours and theme options
p <- p + scale_colour_manual(values = c("blue", "red"))
p <- p + labs(y = "SALES",
              x = "Year",
              colour = "Parameter")
p <- p + theme(legend.position = c(0.8, 0.9))
p

所以这段代码并没有给我很好的结果。我的意图是有一个像下面的图片一样的情节,所以任何人都可以帮助我如何修复上面的代码并制作一个像下面的图片一样的情节?

在此处输入图像描述

标签: rggplot2

解决方案


尝试使用比例因子。这种绘图的关键是使用比例因子来调整第二个轴。这里的代码:

library(ggplot2)
library(dplyr)
#Scale factor
sf <- max(DATA_TEST$SALES)/max(DATA_TEST$EATR)
#Plot
p <- ggplot(DATA_TEST, aes(x = Year))+
  geom_line(aes(y = SALES,,colour = "SALES",group=1),alpha=2)+
  geom_line(aes(y = EATR*sf,colour = "EFFECTIVE RATE",group=1))+
  scale_y_continuous(sec.axis = sec_axis(~./sf, name = "EFFECTIVE RATE"))+
  scale_colour_manual(values = c("blue", "red"))+
  labs(y = "SALES",
       x = "Year",
       colour = "Parameter")+
  theme(legend.position = 'bottom')

输出:

在此处输入图像描述

如果需要更多定制:

#Plot 2
p <- ggplot(DATA_TEST, aes(x = Year))+
  geom_line(aes(y = SALES,,colour = "SALES",group=1),alpha=2,size=1)+
  geom_line(aes(y = EATR*sf,colour = "EFFECTIVE RATE",group=1),size=1)+
  scale_y_continuous(limits = c(0,NA),sec.axis = sec_axis(~./sf, name = "EFFECTIVE RATE"))+
  scale_colour_manual(values = c("blue", "red"))+
  labs(y = "SALES",
       x = "Year",
       colour = "Parameter")+
  theme_bw()+
  theme(legend.position = 'bottom',
        panel.grid = element_blank())

输出:

在此处输入图像描述


推荐阅读