在ggplot2中绘制带有因子水平的垂直线 [英] drawing vertical line with factor levels in ggplot2

查看:64
本文介绍了在ggplot2中绘制带有因子水平的垂直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在x轴上存在 factor ,则在添加 geom_vline 时会遇到一些麻烦.我想转换成 x_value factor 并用 x_line 列画一条垂直线.

类似的帖子可能就是这个.

I have some trouble with adding geom_vline if there is a factor in the x axis. I would like to convert to x_value to factor and draw a vertical line with x_line column.

a similar post may be this.

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

but it did not worked even if I followed the posted solutions as seen below

Here is the short version of the problem

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)

Error in UseMethod("rescale") : no applicable method for 'rescale' applied to an object of class "factor"

then by following this Issue with a drawing a vertical line in ggplot for categorical variable x-axis in R and this geom_vline vertical line on x-axis with categorical data: ggplot2

I tried

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)

Error: ggplot2 doesn't know how to deal with data of class uneval

How can I make this work? Thanks!

解决方案

Just don't convert x_vline to a factor:

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)

这篇关于在ggplot2中绘制带有因子水平的垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆