I am trying to overlay a line on a bar plot using ggplot2. Everything goes as expected until I try to specify the y-range for line plot. In this case a warning occurs (Removed 9 rows containing missing values (geom_bar).
), and bar plot is not visible. How can I fix this?
Data:
example <- data.frame(
week = round(runif(50, min = 1, max = 10), 0),
y_0 = round(runif(50, min = 1000, max = 10000), 2),
x_0 = round(runif(50, min = 100, max = 1000), 2)
)
grouped_data <- example %>% group_by(week) %>% summarise(x_1 = sum(x_0, na.rm = T),
y_1 = sum(y_0, na.rm = T))
grouped_data$x_1 <- grouped_data$x_1*100/grouped_data$y_1
First attempt (OK):
coef <- max(grouped_data$x_1)/max(grouped_data$y_1)
grouped_data %>%
ggplot() +
aes(x = week) +
geom_histogram(aes(y = y_1 * coef), stat = 'identity', alpha = 0.3, color = NA) +
geom_line(aes(y = x_1)) +
scale_y_continuous(sec.axis = sec_axis(~./coef)) +
theme_bw()
Second attempt (shows without bar graph + warning):
min_x <- min(grouped_data$x_1)
max_x <- max(grouped_data$x_1)
coef <- (max_x - min_x)/max(grouped_data$y_1)
grouped_data %>%
ggplot() +
aes(x = week) +
geom_histogram(aes(y = y_1 * coef + min_x), stat = 'identity', alpha = 0.3, color = NA) +
geom_line(aes(y = x_1)) +
scale_y_continuous(limits=c(min_x,max_x), sec.axis = sec_axis(~./coef - min_x/coef)) +
theme_bw()