在绘制 glm 拟合时更改 ggplot2 中的轴标签
Change axis lables in ggplot2 while glm fit is ploted
我遇到以下问题:
我的数据是这样的
NO Income_before_taxes Income_aftere_taxes educationLevel
1: 27757 27313 1
2: 40147 38148 2
3: 52240 47880 3
4: 63061 57027 4
5: 92409 78738 5
6: 132985 106661 6
我想绘制 Income_aftere_taxes ~ educationLevel 的 glm 拟合。
我使用以下代码执行此操作:
ggbox <- ggplot(data = fullDataSet, aes(x = educationLevel, y = Income_aftere_taxes))
ggbox <- ggbox + geom_point()
ggbox <- ggbox + geom_smooth(method = "glm")
结果如下所示:
但是,如果我想将 X 轴的轴标签更改为 c("lower than high school"、"high school"、"college"、"associate degree"、"bachelor"、"master and PhD"),这是行不通的。
要使用 scale_x_descrete 设置标签,我需要将 x 轴输入 "educationLevel" 转换为因子。然而,这会破坏 glm 拟合。
所以,总而言之,我可以绘制 glm 拟合图或更改 x 轴标签。但我需要在一个地块上同时使用这两个选项。有办法实现吗?
试试这个:此处显示的标签具有代表性。假设教育水平保持为数字向量,而不是因子或特征。
在这里,我们为标签创建一个字符向量。
mylabels<-c("High School","No High School","Some College","No College",
"College","PhD","Postdoc")
然后我们在 x 轴上使用它。 [-7]
是为了保持问题标签的长度。您可以根据需要更改标签。
library(dplyr)
library(ggplot2)
df %>%
ggplot(aes(x = educationLevel, y = Income_aftere_taxes))+geom_point()+
geom_smooth(method="glm")+
scale_x_continuous(breaks=c(1,2,3,4,5,6),labels=mylabels[-7])
我遇到以下问题: 我的数据是这样的
NO Income_before_taxes Income_aftere_taxes educationLevel
1: 27757 27313 1
2: 40147 38148 2
3: 52240 47880 3
4: 63061 57027 4
5: 92409 78738 5
6: 132985 106661 6
我想绘制 Income_aftere_taxes ~ educationLevel 的 glm 拟合。
我使用以下代码执行此操作:
ggbox <- ggplot(data = fullDataSet, aes(x = educationLevel, y = Income_aftere_taxes))
ggbox <- ggbox + geom_point()
ggbox <- ggbox + geom_smooth(method = "glm")
结果如下所示:
所以,总而言之,我可以绘制 glm 拟合图或更改 x 轴标签。但我需要在一个地块上同时使用这两个选项。有办法实现吗?
试试这个:此处显示的标签具有代表性。假设教育水平保持为数字向量,而不是因子或特征。 在这里,我们为标签创建一个字符向量。
mylabels<-c("High School","No High School","Some College","No College",
"College","PhD","Postdoc")
然后我们在 x 轴上使用它。 [-7]
是为了保持问题标签的长度。您可以根据需要更改标签。
library(dplyr)
library(ggplot2)
df %>%
ggplot(aes(x = educationLevel, y = Income_aftere_taxes))+geom_point()+
geom_smooth(method="glm")+
scale_x_continuous(breaks=c(1,2,3,4,5,6),labels=mylabels[-7])