使用 R 中的 x 和 y 变量在 ggplot 中创建直方图
Create histogram in ggplot with both x and y variables in R
我希望制作一个直方图,显示焦虑症患者(y 轴)在不同年龄组(x 轴)中的分布情况。我不确定如何为此正确编码,因为我想在单个图表上包含 2 个变量。焦虑变量(MOD_SEV_ANX)是二元的(有焦虑为1,无焦虑为0),年龄是连续的。我已经包含了一个 MRE 来尝试说明我正在尝试做什么。
library(ggplot2)
library(tidyverse)
#Here is the data
data=structure(list(AGE = c(40L, 23L, 24L, 18L, 30L, 33L, 32L, 63L,
22L, 24L, 22L, 21L, 23L, 27L, 20L, 65L, 25L, 36L, 59L, 47L, 44L,
31L, 56L, 40L, 53L, 54L, 30L, 23L, 27L, 28L, 38L, 33L, 42L, 39L,
23L, 22L, 25L, 28L, 24L, 44L), MOD_SEV_ANX = c(0, 1, 1, 0, 1,
0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0,
1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1)), row.names = c(NA,
40L), class = "data.frame")
ggplot(data=data, aes(x=AGE,y=mean(MOD_SEV_ANX)))+
geom_histogram(binwidth = 3)
当我尝试 运行 这行代码时,我收到以下错误:“错误:stat_bin() 只能具有 x 或 y 美学。”我该如何解决这个问题?谢谢!
三个选项,分面,并排绘制,或者如果你真的想并排绘制,再加上重新定向以垂直显示直方图。
library(ggplot2)
ggplot(data,aes(x=AGE))+
geom_histogram(bins = 10)+
facet_grid(~MOD_SEV_ANX)+
theme_bw()
ggplot(data,aes(x=AGE,group=MOD_SEV_ANX, fill=factor(MOD_SEV_ANX)))+
geom_histogram(position="dodge", bins = 10)+
theme_bw()
ggplot(data,aes(x=AGE,group=MOD_SEV_ANX, fill=factor(MOD_SEV_ANX)))+
geom_histogram(position="dodge", bins = 10)+
coord_flip() +
theme_bw()
我希望制作一个直方图,显示焦虑症患者(y 轴)在不同年龄组(x 轴)中的分布情况。我不确定如何为此正确编码,因为我想在单个图表上包含 2 个变量。焦虑变量(MOD_SEV_ANX)是二元的(有焦虑为1,无焦虑为0),年龄是连续的。我已经包含了一个 MRE 来尝试说明我正在尝试做什么。
library(ggplot2)
library(tidyverse)
#Here is the data
data=structure(list(AGE = c(40L, 23L, 24L, 18L, 30L, 33L, 32L, 63L,
22L, 24L, 22L, 21L, 23L, 27L, 20L, 65L, 25L, 36L, 59L, 47L, 44L,
31L, 56L, 40L, 53L, 54L, 30L, 23L, 27L, 28L, 38L, 33L, 42L, 39L,
23L, 22L, 25L, 28L, 24L, 44L), MOD_SEV_ANX = c(0, 1, 1, 0, 1,
0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0,
1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1)), row.names = c(NA,
40L), class = "data.frame")
ggplot(data=data, aes(x=AGE,y=mean(MOD_SEV_ANX)))+
geom_histogram(binwidth = 3)
当我尝试 运行 这行代码时,我收到以下错误:“错误:stat_bin() 只能具有 x 或 y 美学。”我该如何解决这个问题?谢谢!
三个选项,分面,并排绘制,或者如果你真的想并排绘制,再加上重新定向以垂直显示直方图。
library(ggplot2)
ggplot(data,aes(x=AGE))+
geom_histogram(bins = 10)+
facet_grid(~MOD_SEV_ANX)+
theme_bw()
ggplot(data,aes(x=AGE,group=MOD_SEV_ANX, fill=factor(MOD_SEV_ANX)))+
geom_histogram(position="dodge", bins = 10)+
theme_bw()
ggplot(data,aes(x=AGE,group=MOD_SEV_ANX, fill=factor(MOD_SEV_ANX)))+
geom_histogram(position="dodge", bins = 10)+
coord_flip() +
theme_bw()