簡體   English   中英

r的ggplot中的雙y軸(條形和線形)

[英]dual y-axis (bar and line) in ggplot in r

我擁有的數據包含四列: 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")

在此處輸入圖片說明

這是一種調整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")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM