[英]Adding a second y axis in R
我設想使用以下數據集創建一個 plot,它將聚集條形圖和折線圖與以下數據相結合:
structure(list(X = 1:14, ORIGIN = c("AUS", "AUS", "DAL", "DAL",
"DFW", "DFW", "IAH", "IAH", "OKC", "OKC", "SAT", "SAT", "SHV",
"SHV"), DEST = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L), .Label = c("ATL", "SEA"), class = "factor"),
flight19.x = c(293L, 93L, 284L, 93L, 558L, 284L, 441L, 175L,
171L, 31L, 262L, 31L, 175L, 0L), flight19.y = c(5526L, 5526L,
6106L, 6106L, 23808L, 23808L, 15550L, 15550L, 2055L, 2055L,
3621L, 3621L, 558L, 558L)), row.names = c(NA, -14L), class = "data.frame")
我已經嘗試使用sec.axis
function 來生成第二個軸。 但是,結果看起來像 plot 行仍然使用第一個 y 軸而不是第二個軸:
p1 <- ggplot()+
geom_bar(data = flight19, aes(ORIGIN, flight19.x, fill = DEST),stat = "identity", position = "dodge" )+
scale_fill_viridis(name = "Destinations", discrete = TRUE)+
labs(y= "Operation Counts", x = "Airports")
p2 <- p1 + geom_line(data = flight19, aes(as.character(ORIGIN), flight19.y, group = 1))+
geom_point(data = flight19, aes(as.character(ORIGIN), flight19.y, group = 1))+
scale_y_continuous(limit = c(0,600),sec.axis = sec_axis(~.*75/10, name = "Total Monthly Operations"))
plot 顯示以下警告:
Warning messages:
1: Removed 12 row(s) containing missing values (geom_path).
2: Removed 12 rows containing missing values (geom_point).
有人可以教我如何讓線 plot 對應於第二軸嗎? 提前非常感謝。
找到一個合適的變換因子,這里我用 50 只是為了得到漂亮的 y 軸標簽
#create x-axis
flight19$x_axis <- paste0(flight19$ORIGIN,'\n',flight19$DEST)
# The transformation factor
#transf_fact <- max(flight19$flight19.y)/max(flight19$flight19.x)
transf_fact <- 50
ggplot(flight19, aes(x = x_axis)) +
geom_bar(aes(y = flight19.x),stat = "identity", fill = "blue") +
geom_line(aes(y = flight19.y/transf_fact,group=1), color = "orange") +
scale_y_continuous(name = "Operation Counts",
limit = c(0,600),
breaks = seq(0,600,100),
sec.axis = sec_axis(~ (.*transf_fact),
breaks = function(limit)seq(0,limit[2],5000),
labels = scales::dollar_format(prefix = "$",suffix = " k",scale = .001),
name = "Total Monthly Operations")) +
xlab("Airports") +
theme_bw()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.