ggplot2中离散x轴的子组。

3

我想在ggplot2(geom_point)中创建一个子分组,这意味着我想根据子组稍微移动离散的x值(见图)。

我可以通过将离散值更改为连续值并添加依赖于子组的偏移值(见图B),然后手动调整x标签来实现。但是我认为可能有一种更优雅的方式来处理间距和标签问题。下面是一个最简示例,希望能清楚地描述我的意思。

library(ggplot2)
set.seed(1)
df <- data.frame(
    ID =       rep(seq(1,8),2),
    group =    rep(LETTERS[1:4],4),
    subgroup = c(rep("a",8),rep("b",8)),
    value = runif(16)
)
df$xpos <- as.numeric(df$group)+(as.numeric(df$subgroup)/4)


ggplot(data=df, aes(x=group, y= value, color=subgroup))+
  geom_point()+
    ggtitle("How it is")

ggplot(data=df, aes(x=xpos, y= value, color=subgroup))+
  geom_point() +
    ggtitle("How I would like it (without adjusted xAxes Labels)")

enter image description here

1个回答

4
我们可以使用position_dodge:
library(ggplot2)
ggplot(data=df, aes(x=group, y= value, color=subgroup))+
  geom_point(position=position_dodge(width=0.5))+
  ggtitle("How it is")

插入图像描述


数据

set.seed(1)
df <- data.frame(
    ID =       rep(seq(1,8),2),
    group =    rep(LETTERS[1:4],4),
    subgroup = c(rep("a",8),rep("b",8)),
    value = runif(16)
)

谢谢,运行得很好。 作为后续问题:是否有一种方法将其与X轴上的抖动结合起来? - kEks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接