R中的因子变量的线图

时间:2014-07-29 08:54:30

标签: r plot

如何根据因子变量在两个观测值之间绘制R线?

我有两个时间'分数,早期和晚期,编码为分类

plotdata <- structure(list(
               x = structure(1:2, .Label = c("early", "late"), class = "factor"), 
               y = 1:2
               ),
            .Names = c("x", "y"), row.names = c(NA, -2L), class = "data.frame"
)

我只得到一个条形图:

plot(plotdata)

我也尝试将变量编码为0和1,但随后我得到一个连续轴。

1 个答案:

答案 0 :(得分:5)

假设你的数据是

d <- structure(list(x = structure(1:2, .Label = c("early", "late"), class = "factor"), 
    y = 1:2), .Names = c("x", "y"), row.names = c(NA, -2L), class = "data.frame")
d
#       x y
#   early 1
#    late 2

基础R

plot(as.numeric(d$x), d$y, type = "l", xaxt = "n")
axis(1, labels = as.character(d$x), at = as.numeric(d$x))

使用ggplot2

library(ggplot2)
ggplot(d, aes(x = x, y = y)) + geom_line(aes(group = 1))