[英]dual y-axis (bar and line) in ggplot in r
我擁有的數據包含四列: x
, y_cnt
, y1_rate
, y2_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_rate
和y2_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.