首页 文章

ggplot2用一些x轴跳汰绘制3个因子

提问于
浏览
7

我想用ggplot2 geom_point创建一个点图,其中连续变量按不同因素分层 .

这很复杂,也许我试图在一个图表中显示太多,但我有三个影响事物的不同因素

我想像这样展示它

p <- ggplot(mtcars[,c(1,2,10,11)], aes(factor(cyl), mpg))
p + geom_point(aes(colour = factor(gear), shape=factor(carb)))

enter image description here

但是我想把因子(齿轮)分开,即对于x轴上的三个因子(cyl)值中的每一个,我想要x轴上不同因子(齿轮)颜色之间的小距离

即在因子(cyl)== 4中,因子(齿轮)== 3是3.9,因子(齿轮)== 4是4,因子(齿轮)== 5是4.1 . 对于每个因子(cyl)值重复这一过程 .

希望有道理

NB这是一个玩具的例子 . 我会使用分类,非数字值而不是分解数字来做它;我意识到3.9 / 4.1的值很令人困惑 .

2 回答

  • 9

    subset 是这样做的一种方法 . 通过 gears 对数据进行子集,然后依次为每个子集定位点集 .

    library(ggplot2)
    
    p <- ggplot()
    p + geom_point(data = subset(mtcars[,c(1,2,10,11)], gear == 3), aes(x = as.numeric(factor(cyl)) - 0.1, y = mpg, colour = factor(gear), shape=factor(carb))) +
        geom_point(data = subset(mtcars[,c(1,2,10,11)], gear == 4), aes(x = as.numeric(factor(cyl)), y = mpg, colour = factor(gear), shape=factor(carb))) +
        geom_point(data = subset(mtcars[,c(1,2,10,11)], gear == 5), aes(x = as.numeric(factor(cyl)) + .1, y = mpg, colour = factor(gear), shape=factor(carb))) +
       scale_x_continuous("Cylinders", breaks = c(1,2,3), labels = c(4,6,8), expand = c(.2,0))
    

    enter image description here

  • 4

    使用 facet_grid() 和mtcars示例:

    library(ggplot2)
    data(mtcars)
    
    p <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_point(aes(colour=factor(carb)))
    p + facet_grid(. ~ gear)
    

    By number of gears

相关问题