如何在R中绘制直方图?

huangapple go评论80阅读模式
英文:

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.
如何在R中绘制直方图?

答案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)

如何在R中绘制直方图?

英文:

You can color the bars by using the fill argument of geom_bar().

library(tidyverse)

df &lt;- data.frame(
  age_at_visit = sample(67:112, 100000, replace = TRUE),
  year = sample(2008:2012, 100000, replace = TRUE)
)

df &lt;-
  df |&gt;
  mutate(age_group = cut(
    age_at_visit,
    breaks = c(67, 70, 80, 90, 112),
    labels = c(&quot;67-69&quot;, &quot;70-79&quot;, &quot;80-89&quot;, &quot;90-112&quot;),
    include.lowest = TRUE
  ))

df |&gt;
  add_count(year) |&gt; 
  ggplot() +
  geom_bar(aes(year, fill = age_group), color = 1) +
  scale_fill_brewer(name = &quot;Age at Visit&quot;) +
  scale_y_continuous(label = scales::comma) +
  labs(x = &quot;Year of Visit&quot;,
       y = &quot;Number of Visits&quot;) +
  geom_line(aes(x = year, y = n), linewidth = 2)

如何在R中绘制直方图?<!-- -->

huangapple
  • 本文由 发表于 2023年7月31日 23:56:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76805271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定