简体   繁体   English

ggplot2 中离散 x 轴的子组

[英]subgroups for discrete x Axis in ggplot2

I would like to create a sub grouping in a ggplot2 (geom_point), meaning that I would like to shift discrete x values slightly according to a subgroup (see Figure).我想在 ggplot2 (geom_point) 中创建一个子分组,这意味着我想根据子组稍微移动离散的 x 值(见图)。

I could achieve that by changing the discrete values to continuous and add a subgroup dependent shift value (see Fig.B), and than manually adjust the x labels.我可以通过将离散值更改为连续值并添加与子组相关的移位值来实现这一点(见图 B),然后手动调整 x 标签。 But I thought there is probably a more elegant way which deals with spacing and labeling issues.Below is a minimal example which hopefully describes what I mean.但我认为可能有一种更优雅的方式来处理间距和标签问题。下面是一个最小的例子,希望能描述我的意思。

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)")

在此处输入图像描述

We can use position_dodge :我们可以使用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")

在此处输入图像描述


Data数据

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)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM