代码之家  ›  专栏  ›  技术社区  ›  Lumos

ggplot具有所有x轴值的x轴标签

  •  29
  • Lumos  · 技术社区  · 7 年前

    我在密谋 ggplot 具有 geom_point . x轴是个人ID,y轴是变量A。如何在x轴上绘制所有和个人ID值,而不重叠标签?ID可能不连续。

    df样本(实际行长得多)

    > df
    ID     A
    1      4
    2      12
    3      45
    5      1
    

    绘图代码:

    ggplot(df, aes(x = ID, y = A)) + geom_point()
    

    上述代码以间隔显示x轴,但不显示个人ID。

    谢谢

    2 回复  |  直到 6 年前
        1
  •  76
  •   f.lechleitner    7 年前

    这就是你要找的吗?

    ID <- 1:50
    A <- runif(50,1,100)
    
    df <- data.frame(ID,A)
    
    ggplot(df, aes(x = ID, y = A)) + 
      geom_point() + 
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
      scale_x_continuous("ID", labels = as.character(ID), breaks = ID)
    

    这将产生以下图像:

    enter image description here

    所以每个ID值都有一个标签。如果你想删除网格线(对我来说太多了),你可以通过添加 theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

    编辑: 更简单的方法是只使用ID作为绘图的因子。这样地:

    ggplot(df, aes(x = factor(ID), y = A)) + 
      geom_point() + 
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
      xlab("ID")
    

    enter image description here

    这种方法的优点是不会从丢失的ID中获得空白

    编辑2: 关于重叠标签的问题:我猜想它来自于要绘制的大量ID。有几种方法可以解决这个问题。假设你的情节是这样的:

    enter image description here

    一种想法是通过修改轴的break参数来隐藏x轴的每三个标签:

    ggplot(df, aes(x = factor(ID), y = A)) + 
      geom_point() + 
      scale_x_discrete(breaks = ID[c(T,F,F)]) +
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
      xlab("ID")
    

    这导致了:

    enter image description here

    如果不选择隐藏标签,则可以将绘图拆分为子绘图。

    df$group <- as.numeric(cut(df$ID, 4))
    
    ggplot(df, aes(x = factor(ID), y = A)) + 
      geom_point() + 
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
      xlab("ID") +
      facet_wrap(~group, ncol = 1, scales = "free_x")
    

    这导致了:

    enter image description here

        2
  •  -1
  •   stevec Zxeenu    3 年前

    只需添加 + xlim() + ylim() 显示完整的x轴和y轴(即,使x轴和y轴从零开始)。

    可复制示例

    如果这是ggplot:

    iris %>% 
      ggplot(aes(x=Sepal.Length, y=Sepal.Width)) +
      geom_point() 
    

    enter image description here

    只需将这两条线相加,即可使x轴和y轴从零开始 :

    iris %>% 
      ggplot(aes(x=Sepal.Length, y=Sepal.Width)) +
      geom_point() +     
      xlim(0, 8.2) +     # add this line for x axis limits
      ylim(0, 4.5)       # add this line for y axis limits
    

    enter image description here