[英]How to draw secondary axis of a bar chart in R?
我有以下data.frame
和R-code
,我正在嘗試生成一個bar graph
,其中輔助軸上的precipation
應該反轉。
library(tidyverse)
DF <- data.frame(Month = 1:12, Flow = c(1,2,5,30,45,50,40,25,15,10,4,1.2),
Prec = c(24,17,23,31,55,93,80,69,13,32,25,25))
ggplot(DF,aes(x = Month))+
geom_bar(aes(y = Flow), stat = "identity", color="blue", fill= "blue", width = 0.5)+
geom_bar(aes(y = Prec*0.5), stat = "identity", color="red", fill= "red", width = 0.5)+
scale_y_continuous("Streamflow", sec.axis = sec_axis(~ . /0.5, name = "Precipitation (mm)"), trans = "reverse")
輔助軸在這里並不是真正的問題。 問題是酒吧位於不同的基線上。 即使有不同的組,geom 層geom_bar
和geom_col
需要從相同的基線開始,所以我認為沒有辦法使用這些 geom 來做到這一點。 但是,重塑數據以使用geom_rect
繪制 plot 並不難。
DF %>%
pivot_longer(Flow:Prec) %>%
group_by(Month) %>%
summarize(xmin = Month - 0.25,
xmax = Month + 0.25,
ymax = ifelse(name == "Prec", 150, value),
ymin = ifelse(name == "Prec", 150 - value, 0),
name = name) %>%
ggplot(aes(Month, ymin, fill = name)) +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax)) +
scale_y_continuous(name = "Flow", expand = c(0, 0),
sec.axis = sec_axis(~ 150 - .x, name = "Precipitation")) +
theme_classic(base_size = 20) +
scale_fill_manual(values = c("red", "blue"),
labels = c("Steam flow", "Precipitation"), name = NULL) +
scale_x_continuous(breaks = 1:12, labels = month.abb) +
theme(panel.border = element_rect(fill = NA),
legend.position = c(0.85, 0.4))
使用兩個geom_bar
和ggplot_build
的另一種選擇。 在這里,您可以通過將原點設為“max_flow”(流量的最大值)來更改藍條的原點。 這是一個可重現的示例:
library(ggplot2)
DF <- data.frame(Month = 1:12, Flow = c(1,2,5,30,45,50,40,25,15,10,4,1.2),
Prec = c(24,17,23,31,55,93,80,69,13,32,25,25))
# plot
p <- ggplot(DF,aes(x = Month))+
geom_bar(aes(y = Flow, fill= "red"), stat = "identity", width = 0.5)+
geom_bar(aes(y = Prec*0.5, fill = "blue"), stat = "identity", width = 0.5)+
scale_x_continuous(breaks = 1:12, labels = month.abb) +
scale_y_continuous("Streamflow", sec.axis = sec_axis(~ rev(. /0.5), name = "Precipitation (mm)"), expand = c(0,0)) +
scale_fill_manual(values = c("blue", "red"), labels = c("Precipitation", "Steam flow"), name = NULL) +
theme_classic() +
theme(panel.border = element_rect(fill = NA), legend.position = c(0.85, 0.4))
# Max value to use as origin
max_flow <- max(DF$Flow)
# Transform bars to upper side
q <- ggplot_build(p)
q$data[[2]]$ymin <- max_flow
q$data[[2]]$ymax <- max_flow-q$data[[2]]$ymax
q <- ggplot_gtable(q)
plot(q)
使用reprex v2.0.2創建於 2022-09-11
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.