水平轴上有因子的散点图 [英] Scatter plot with factor on horizontal axis
问题描述
我正在尝试生成一个简单的散点图,在 x 轴上有一个因子.结果图显示水平线而不是点(不幸的是无法上传图像).
I am trying to produce a simple scatter plot with a factor on the x-axis. The resulting plot shows horizontal lines rather than dots (can't upload the image, unfortunately).
根据我教授的要求,根据 Dobson、Bennett 的 广义线性模型简介 中的示例 3.5,将一些 SAS 代码转录为 R.目的是向我的同学介绍 R,所以我试图保持它尽可能简单和干净.
Transcribing some SAS code to R based on example 3.5 from An Introduction to Generalized Linear Models by Dobson, Bennett, per my professor's request. Purpose is to introduce my classmates to R, so I am trying to keep this as simple and clean as possible.
dat <- data.frame(age_group = c("30-34", "35-39", "40-44",
"45-49", "50-54", "55-59", "60-64", "65-69"),
deaths = c(1, 5, 5, 12, 25, 38, 54, 65),
population = c(17742, 16554, 16059, 13083, 10784, 9645, 10706, 9933))
dat <- within(dat, {
rate <- deaths / population * 100000
lograte <- log(deaths / population * 100000)
})
还有我的剧情
with(dat, plot(age_group, lograte, pch=19))
不会产生我想要的点".我有一个 hacked together 解决方案,稍后我会发布,但想看看是否有更好的方法.再次抱歉无法上传图片.
does not produce the 'dots' that I would like. I have a hacked together solution which I'll post later, but wanted to see if there was a better way. Again, apologies that I can't upload the image.
推荐答案
使用 base R 你可以这样做:
通过 xaxt="n"
压住 x 轴,然后手动添加.
Using base R you can do it as follows:
Surpress the x-axis by xaxt="n"
and add it afterwards manually.
plot(1:nrow(dat), dat$lograte, xaxt="n", xlab="age_group", ylab="lograte", pch=19)
axis(1, at=1:8, labels=dat$age_group)
您可以使用 ggplot2
而不是基本的 R 绘图来实现它:
You can achieve it using ggplot2
instead of the base R plot:
require(ggplot2)
ggplot(dat, aes(x=age_group, y=lograte)) + geom_point()
这篇关于水平轴上有因子的散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!