# [Case A] Both the contingency table and the plot are based on tidy data
# Data
df <- data.frame(variant = c(rep("AA", times = 10),
rep("AA", times = 80),
rep("AB", times = 50),
rep("AB", times = 40),
rep("BB", times = 90),
rep("BB", times = 10)),
fruit_daily = c(rep("yes", times = 10),
rep("no", times = 80),
rep("yes", times = 50),
rep("no", times = 40),
rep("yes", times = 90),
rep("no", times = 10)))
# Contingency table
df |>
janitor::tabyl(fruit_daily, variant)
# Bar plot (using relevel to maintain the bars ordered as in the question)
df |>
dplyr::mutate(fruit_daily = forcats::fct_relevel(fruit_daily, "yes", "no")) |>
ggplot2::ggplot(aes(fill = fruit_daily, x = variant)) +
geom_bar(position = position_dodge())
然而,您 * 可以 * 从列联表开始构建条形图:
# [Case B] A bar plot from the contingency table using janitor::tabyl
df |>
janitor::tabyl(variant, fruit_daily) |>
tidyr::gather(key = answers, value = how_many, no:yes) |>
dplyr::mutate(answers = forcats::fct_relevel(answers, "yes", "no")) |>
ggplot2::ggplot(aes(y = how_many, x = variant, fill = answers)) +
geom_col(position = position_dodge())
# [Case C] A bar plot from the contingency table using base table function
as.data.frame(table(df)) |>
dplyr::mutate(fruit_daily = forcats::fct_relevel(fruit_daily, "yes", "no")) |>
ggplot2::ggplot(aes(y = Freq, x = variant, fill = fruit_daily)) +
geom_col(position = position_dodge())
2条答案
按热度按时间dgtucam11#
您可能希望创建一个单独的表。将图例提取为单独的
grob
,然后单独布局每个部分。样本代码:
情节:
样品数据:
bogh5gae2#
上一个答案建议如何在列联表之上构建条形图,这里我建议如何从列联表构建条形图。
推荐的工作流程是基于整洁的数据构建列联表和图,下面是一个例子:
然而,您 * 可以 * 从列联表开始构建条形图:
最后,从基表函数(受this solution启发)开始执行相同的任务: