我正在尝试使用ggplot2在条形图上覆盖一条线。一切按预期进行,直到我尝试为线图指定y范围。在这种情况下,会发生警告(Removed 9 rows containing missing values (geom_bar).
),并且看不到条形图。我该如何解决?
数据:
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
首次尝试(确定):
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()
第二次尝试(显示时没有条形图和警告):
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()