首页 文章

在ggplot2中绘制因子水平的垂直线

提问于
浏览
0

如果x轴上有 factor ,我在添加 geom_vline 时会遇到一些麻烦 . 我想将 x_value 转换为 factor 并绘制一条带有 x_line 列的垂直线 .

类似的帖子可能是这个 .

geom_vline vertical line on x-axis with categorical data: ggplot2

但即使我按照下面所示的方式发布,它也没有用

这是问题的简短版本

df <- data.frame(x_value=c(rep(seq(1,5),2)), y_value=c(rnorm(10,5,1)),x_vline=3, gr=rep(c(1,2),c(5,5)))


> df
   x_value  y_value x_vline gr
1        1 6.589680       3  1
2        2 4.937223       3  1
3        3 6.934755       3  1
4        4 4.407492       3  1
5        5 6.321616       3  1
6        1 7.068435       3  2
7        2 4.379096       3  2
8        3 8.138772       3  2
9        4 5.814828       3  2
10       5 5.828453       3  2

library(ggplot2)

ggplot(df, aes(x=factor(x_value), y=y_value)) +

    geom_point(size=3, aes(colour=factor(gr)))+

    facet_wrap(~gr)+

    geom_vline(aes(xintercept=factor(x_vline)), linetype="dashed",colour="blue",size=0.7)

UseMethod中的错误(“rescale”):没有适用于“rescale”的方法应用于类“factor”的对象

然后按照这个Issue with a drawing a vertical line in ggplot for categorical variable x-axis in Rgeom_vline vertical line on x-axis with categorical data: ggplot2

我试过了

ggplot(df, aes(x=factor(x_value), y=y_value)) +

    geom_point(size=3, aes(colour=factor(gr)))+

    facet_wrap(~gr)+

    #geom_vline(aes(xintercept=factor(x_vline)), linetype="dashed",colour="blue",size=0.7)

    geom_vline(df,aes(xintercept=which(levels(factor(x_value)) %in% levels(factor(x_vline)))), linetype="dashed",colour="blue",size=0.7)

错误:ggplot2不知道如何处理类uneval的数据

我怎样才能做到这一点?谢谢!

1 回答

  • 1

    只是不要将 x_vline 转换为一个因素:

    ggplot(df, aes(x=factor(x_value), y=y_value)) +
        geom_point(size=3, aes(colour=factor(gr)))+
        facet_wrap(~gr)+
        geom_vline(aes(xintercept=x_vline), linetype="dashed",colour="blue",size=0.7)
    

    enter image description here

相关问题