繁体   English   中英

如何在 R 中绘制条形图的辅助轴?

[英]How to draw secondary axis of a bar chart in R?

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

在此处输入图像描述

目标:我想看到像下面这样的 plot 在此处输入图像描述

辅助轴在这里并不是真正的问题。 问题是酒吧位于不同的基线上。 即使有不同的组,geom 层geom_bargeom_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_barggplot_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM