【问题标题】:dual y-axis (bar and line) in ggplot in rr中的ggplot中的双y轴(条形和线形)
【发布时间】:2019-08-23 03:01:56
【问题描述】:

我的数据包含四列: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 在辅助 y 轴上。

这是它在 Excel 中的样子:

更新:

这就是我迄今为止所做的。下图好像只显示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")

【问题讨论】:

标签: r ggplot2


【解决方案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")

【讨论】:

  • 我刚刚尝试运行您的代码并收到以下错误:``` UseMethod 中的错误(“as.fun_list”):没有适用于 'as.fun_list' 的方法应用于类对象“公式”```。你知道出了什么问题吗?
  • 您是在使用示例数据还是新的东西?我重新加载了 R,加载了您的示例数据,并且运行我的代码没有问题。我建议移除管道(%&gt;%)并查看哪个步骤导致了该错误,因为这对我来说并不明显。