英文:
How to plot a histogram in R?
问题
有人能帮我在R中绘制这个直方图吗?我不知道如何添加“Age at visit”列。我的数据包括年份和年龄。
英文:
Can anybody help me to plot this histogram in R. I dont know how to add the column "Age at visit".
My data includes year and age.
答案1
得分: 2
你可以使用geom_bar()
的fill
参数来为条形图着色。
library(tidyverse)
df <- data.frame(
age_at_visit = sample(67:112, 100000, replace = TRUE),
year = sample(2008:2012, 100000, replace = TRUE)
)
df <-
df %>%
mutate(age_group = cut(
age_at_visit,
breaks = c(67, 70, 80, 90, 112),
labels = c("67-69", "70-79", "80-89", "90-112"),
include.lowest = TRUE
))
df %>%
add_count(year) %>%
ggplot() +
geom_bar(aes(year, fill = age_group), color = 1) +
scale_fill_brewer(name = "Age at Visit") +
scale_y_continuous(label = scales::comma) +
labs(x = "Year of Visit",
y = "Number of Visits") +
geom_line(aes(x = year, y = n), linewidth = 2)
英文:
You can color the bars by using the fill
argument of geom_bar()
.
library(tidyverse)
df <- data.frame(
age_at_visit = sample(67:112, 100000, replace = TRUE),
year = sample(2008:2012, 100000, replace = TRUE)
)
df <-
df |>
mutate(age_group = cut(
age_at_visit,
breaks = c(67, 70, 80, 90, 112),
labels = c("67-69", "70-79", "80-89", "90-112"),
include.lowest = TRUE
))
df |>
add_count(year) |>
ggplot() +
geom_bar(aes(year, fill = age_group), color = 1) +
scale_fill_brewer(name = "Age at Visit") +
scale_y_continuous(label = scales::comma) +
labs(x = "Year of Visit",
y = "Number of Visits") +
geom_line(aes(x = year, y = n), linewidth = 2)
<!-- -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论