我正在尝试绘制三个变量(SA,SA1,SA2),其中两个变量(SA&SA2)在左侧y轴上,一个变量(SA1)在右侧辅助y轴上。我尝试在左侧 y Axis 上使用 limits = c(1e15,5e15)
修复 Axis 限制,同时尝试将辅助轴限制在 limits = c(3e17,4.2e17)
之间> 但我无法用我的自定义限制绘制第二 Axis 。 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
仅创建一个新 Axis ,但它不会更改您的数据,也不能用于绘制数据。
为了能够绘制大范围两组的数据,您需要首先缩小 SA1。
在这里,我将其除以 100 来缩小它(因为 SA1 的最大值与 SA 和 SA2 的最大值之间的比率接近 100),并且我还以更适合 的更长格式 reshape 您的数据帧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>)
关于r - 使用 ggplot 绘制辅助轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59956953/