使用 ggplot 绘制次轴

Plotting secondary axis using ggplot

我正在尝试绘制三个变量 (SA、SA1、SA2),其中两个变量 (SA& SA2) 在左侧 y 轴上,一个变量 (SA1) 在右侧副 y 轴上。我尝试在左侧 y 轴上使用 limits = c(1e15,5e15) 修复轴限制,同时尝试将次轴限制在 limits = c(3e17,4.2e17) 之间,但我无法使用自定义限制绘制次轴。 DATA Link

library(ggplot2)
test <- read.xlsx2("filepath/test.xlsx", 1, header=TRUE)
View(test)
test$SA=as.numeric(levels(test$SA))[test$SA]
test$SA1=as.numeric(levels(test$SA1))[test$SA1]
test$SA2=as.numeric(levels(test$SA2))[test$SA2]
g <- ggplot(test,aes(x=year, y=  SA, group = 1)) + geom_line(mapping = aes(x = test$year, y = test$SA)) 
+ geom_line(mapping = aes(x = test$year, y = test$SA2), color = "red") +  geom_line(mapping = aes(x = test$year, y = test$SA1), size = 1, color = "blue")
 g+scale_y_continuous(name = "primary axis title",
+                      sec.axis = sec_axis(~./5, name = "secondary axis title (SA1)"))

@dc37 的最终解决方案给了我以下结果:

ggplot(subset(DF, Var != "SA1"), aes(x = year, y = val, color = Var))+
  geom_line()+
  scale_y_continuous(name = "Primary axis", sec.axis = sec_axis(~.*100, name = "Secondary"))

谢谢

参数 sec.axis 只是创建一个新轴,但它不会更改您的数据,也不能用于绘制数据。

要能够绘制出范围较大的两组数据,您需要先缩小 SA1。

在这里,我通过将它除以 100 来缩小它(因为 SA1 的最大值与 SA 和 SA2 的最大值之间的比率接近 100)并且我还以更适合 ggplot2:

library(lubridate)
df$year = parse_date_time(df$year, orders = "%Y") # To set year in a date format
library(dplyr)
library(tidyr)
DF <- df %>% mutate(SA1_100 = SA1/100) %>% pivot_longer(.,-year, names_to = "Var",values_to = "val")

# A tibble: 44 x 3
    year Var         val
   <int> <chr>     <dbl>
 1  2008 SA      1.41e15
 2  2008 SA1     3.63e17
 3  2008 SA2     4.07e15
 4  2008 SA1_100 3.63e15
 5  2009 SA      1.53e15
 6  2009 SA1     3.77e17
 7  2009 SA2     4.05e15
 8  2009 SA1_100 3.77e15
 9  2010 SA      1.52e15
10  2010 SA1     3.56e17
# … with 34 more rows

然后,您可以使用(我对数据帧进行子集化以删除 "SA1" 并保留转换后的列 "SA1_100")来绘制它:

library(ggplot2)
ggplot(subset(DF, Var != "SA1"), aes(x = year, y = val, color = Var))+
  geom_line()+
  scale_y_continuous(name = "Primary axis", sec.axis = sec_axis(~.*100, name = "Secondary"))

顺便说一句,在ggplot2中,您不需要使用$设计列,只需写上它的名称即可。

数据

structure(list(year = 2008:2018, SA = c(1.40916e+15, 1.5336e+15, 
1.52473e+15, 1.58394e+15, 1.59702e+15, 1.54936e+15, 1.6077e+15, 
1.59211e+15, 1.73533e+15, 1.7616e+15, 1.67771e+15), SA1 = c(3.63e+17, 
3.77e+17, 3.56e+17, 3.68e+17, 3.68e+17, 3.6e+17, 3.6e+17, 3.68e+17, 
3.55e+17, 3.58e+17, 3.43e+17), SA2 = c(4.07e+15, 4.05e+15, 3.94e+15, 
3.95e+15, 3.59e+15, 3.53e+15, 3.43e+15, 3.2e+15, 3.95e+15, 3.03e+15, 
3.16e+15)), row.names = c(NA, -11L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x56412c341350>)