
I am trying to show stacked bar graph (x=year, y=population_count(different cut-off of calcium)) and line plot (x=year, y=calcium) simultaneously. Something like the attachment. I tried to create the stacked bar graph first, and add geom_line. But it kept showing the aesthestics issue.Then I tried to create the two graphs separately, but had trouble overlapping them. I have attached my code below, which is the step I took to create two graphs

# Categorize calcium intake into intervals
data$calc_category <- cut(data$calc,
breaks = c(0, 1000, 1200, 2000, Inf),
labels = c("<EAR", ">=EAR,<RDA", ">=RDA,<UL", ">=UL"),
include.lowest = TRUE)
# Calculate the proportion of population in each interval for each survey year
prop_data <- data %>%
group_by(SDDSRVYR, calc_category) %>%
summarise(count = n()) %>%
group_by(SDDSRVYR) %>%
mutate(prop_count = count / sum(count))
prop_data$calc_category <- factor(prop_data$calc_category,
levels = c(">=UL", ">=RDA,<UL", ">=EAR,<RDA", "<EAR"))
#rename survey year
prop_data$SDDSRVYR <- factor(prop_data$SDDSRVYR,
levels = unique(prop_data$SDDSRVYR),
labels = c("2007-2008", "2009-2010", "2011-2012", "2013-2014", "2015-2016", "2017-2018"))
# Create the stacked bar graph
ggplot(prop_data, aes(x = SDDSRVYR, y = prop_count, fill = calc_category)) +
geom_bar(stat = "identity", width=0.5) +
labs(title = "Proportion of Population by Calcium Intake Interval and Survey Year",
x = "Survey Cycle (Year)",
y = "Proportion of Population") +
scale_fill_brewer(palette = "Blues", name = "Calcium Intake") +
theme_minimal()+
theme(legend.position = "bottom",
legend.box = "horizontal")
### line plot #####
# calculate survey mean of calcium_total
# Define the survey design
survey_design <- svydesign(ids = ~1, weights = ~WTDRD1, data = data)
# Calculate the weighted mean of calc for each SDDSRVYR
mean_calc <- svyby(~calc, ~SDDSRVYR, design = survey_design, FUN = svymean)
# Print the mean_calc dataframe
print(mean_calc)
#rename survey year variable level
mean_calc$SDDSRVYR <- factor(mean_calc$SDDSRVYR,
levels = unique(mean_calc$SDDSRVYR),
labels = c("2007-2008", "2009-2010", "2011-2012", "2013-2014", "2015-2016", "2017-2018"))
#line plot of mean calcium intake
ggplot(mean_calc, aes(x = SDDSRVYR, y = calc)) +
geom_point(color = "black", size = 0.5) +
geom_line(color = "black", aes(group = 1), size = 1) +
geom_errorbar(aes(ymin = calc - se, ymax = calc + se), width = 0.06) +
labs(title = "Mean Calcium Intake by Survey Year",
x = "Survey Cycle (Year)",
y = "Mean Dietary Calcium Intake (mg/d)") +
scale_y_continuous(limits = c(0, 2000), position = "right") +
theme_minimal()