r的ggplot中的双y轴(条形和线形)

时间:2019-08-23 03:01:56

标签: r ggplot2

我拥有的数据包含四列:xy_cnty1_ratey2_rate

set.seed(123)
x <- seq(1,10)
y_cnt <- rnorm(10, 200, 50)
y1_rate <- runif(10,0,1)
y2_rate <- runif(10,0,1)
df <- data.frame(x, y_cnt, y1_rate, y2_rate)

我需要制作一个图,使得x在x轴上,y1_ratey2_rate都在主y轴上,y_cnt在x轴上次要Y轴。

在Excel中的外观如下:

enter image description here

更新

这就是我到目前为止。下图似乎只显示y1_rate

transf_fact <- max(df$y_cnt)/max(df$y1_rate)

# Plot
ggplot(data = df,
       mapping = aes(x = as.factor(x),
                     y = y_cnt)) +
  geom_col(fill = 'red') +
  geom_line(aes(y = transf_fact * y1_rate), group = 1) + 
  geom_line(aes(y = transf_fact * y2_rate)) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . / transf_fact, 
                                         name = "Rate"))+
  labs(x = "X")

enter image description here

1 个答案:

答案 0 :(得分:1)

这是一种调整rate变量的比例,然后将所有序列收集为长格式,然后显示变量及其各自几何的方法。

transf_fact <- max(df$y_cnt)/max(df$y1_rate)

library(tidyverse) # Using v1.2.1

df %>%
  # Scale any variables with "rate" in their name
  mutate_at(vars(matches("rate")), ~.*transf_fact) %>%
  # Gather into long form; 
  #  one column specifying variable, one column specifying value
  gather(y_var, val, -x) %>%

  # Pipe into ggplot; all layers share x, y, and fill/color columns
  ggplot(aes(x = as.factor(x), y = val, fill = y_var)) +
  # bar chart only uses "y_cnt" data
  geom_col(data = . %>% filter(y_var == "y_cnt")) +
  # lines only use non-"y_cnt" data
  geom_line(data = . %>% filter(y_var != "y_cnt"),
            aes(color = y_var, group = y_var),
            size = 1.2) +
  # Use the "fill" aesthetic to control both colour and fill;
  # geom_col typically uses fill, geom_line uses colour
  scale_fill_discrete(aesthetics = c("colour", "fill")) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . / transf_fact, 
                                         name = "Rate")) +
  labs(x = "X")

enter image description here