gpt4 book ai didi

r - 如何在R中绘制条形图的次轴?

转载 作者:行者123 更新时间:2023-12-05 01:49:49 25 4
gpt4 key购买 nike

我有以下data.frameR-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")

enter image description here

目标:我想看到如下图 enter image description here

最佳答案

辅助轴并不是这里真正的问题。问题在于酒吧位于不同的基线上。即使存在不同的组,几何层 geom_bargeom_col 也需要从相同的基线开始,所以我认为没有办法使用这些几何来做到这一点。但是,使用 geom_rect reshape 数据以绘制绘图并不是非常困难。

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))

enter image description here

关于r - 如何在R中绘制条形图的次轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73678280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com