【问题标题】:ggplot2: Factor for x axis with geom_line doesn't workggplot2:带有geom_line的x轴因子不起作用
【发布时间】:2016-07-29 23:46:13
【问题描述】:

我想要一个线图,其中value 被绘制为expt 的函数,var 中的每一层都有一条线:

这是我的数据:

lines <- "
expt,var,value
1,none.p,0.183065327746799
2,none.p,0.254234138384241
3,none.p,0.376477571234912
1,male.p,-1.58289835719949
2,male.p,-1.98591548366901
3,male.p,-2.02814824729229
1,neutral.p,-2.01490302054226
2,neutral.p,-1.88178562088577
3,neutral.p,-1.68089687641625
1,female.p,-3.27294304613848
2,female.p,-3.07711187982237
3,female.p,-2.89652562347054
1,both.p,-2.40011011312792
2,both.p,-2.24495598015741
3,both.p,-2.78501124223834"
con <- textConnection(lines)
data <- read.csv(con)
close(con)

expt 是一个因素:

data$expt <- factor(data$expt)

当我使用geom_point时,一切都按预期工作

ggplot(data, aes(expt, value, colour=var)) + geom_point()

但是当我使用geom_line

ggplot(data, aes(expt, value, colour=var)) + geom_line()

我收到以下错误消息

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

和一个空的情节。当expt 是数字时,它可以工作,但我更喜欢使用一个因子,因为这给了我在 x 轴上的正确标签。这里有什么问题?我发现这非常违反直觉,这适用于点但不适用于线条。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    要在 x 轴上绘制带有因子的折线图,除了 color 之外,您还需要使用 group...

    ggplot(data, aes(expt, value, group=var, color=var)) + geom_line()
    

    给我这个输出:

    【讨论】:

    • 谢谢。我现在明白为什么这是正确的解决方案,但我不明白为什么当 expt 是数字时它会起作用。好像不应该。错误消息也可能不正确。
    • @tmalsburg 这里有一些解释:plotting-lines-and-the-group-aesthetic-in-ggplot2
    猜你喜欢
    • 2013-04-27
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多