【问题标题】:Missing lines ggplot2 graph缺少线条ggplot2图
【发布时间】:2021-12-10 02:33:34
【问题描述】:

使用 ggplot2、dplyr 和 scales 包,我将代码制作成如下图

grafico_4 <- ggplot() +
  ggtitle("Grafico variado") +
  theme(plot.title = element_text(size = 10)) +
  theme(panel.background = element_rect(fill='white', colour='white')) +
  theme( axis.line = element_line(colour = "black", size = 0.5)) +
  scale_y_discrete(limits = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")) +
  scale_x_discrete(limits = c("uno", "", "tres", "", "cinco", "", "siete", "", "nueve", "")) +
  geom_hline(yintercept = 5, linetype = "dotted") +
  ylab("")

但是为什么我在“uno”和“dos”之间有一条线,而不是在“cinco”和“siete”、“siete”和“nueve”之间以及“nueve”之后?如何让线条出现?

【问题讨论】:

    标签: r ggplot2 plot dplyr


    【解决方案1】:

    您所描述的不是限制;它们是 x 轴标签。如果您像这样对限制和标签进行编码,您将获得预期的输出。

    library(ggplot2)
    
    ggplot() +
      ggtitle("Grafico variado") +
      theme(plot.title = element_text(size = 10)) +
      theme(panel.background = element_rect(fill='white', colour='white')) +
      theme( axis.line = element_line(colour = "black", size = 0.5)) +
      scale_y_discrete(limits = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")) +
      scale_x_discrete(
        limits = factor(1:10),
        labels = c("uno", "", "tres", "", "cinco", "", "siete", "", "nueve", "")
      ) +
      geom_hline(yintercept = 5, linetype = "dotted") +
      ylab("")
    

    reprex package (v2.0.1) 于 2021 年 10 月 24 日创建

    【讨论】:

      【解决方案2】:

      scale_x_discrete 的限制参数是放置可能的比例值的地方。但它不能多次显示相同的值。

      所以我能想到的最骇人听闻的解决方案是使用不同的空白字符串:

      scale_x_discrete(limits = c("uno", "", "tres", " ", "cinco", "   ", "siete", "    ", "nueve")) +
      

      这是一个糟糕的解决方案,但我觉得有必要分享。

      编辑:这是一种不同的方法,我认为它依赖于(在我看来)更典型的 ggplot2 语法。我没想到的一个问题是 ggplot2 似乎不想打印 x 轴,即使指定了它的中断和限制,直到“x-space”中存在一个几何图形——即 geom_hline 不会t 触发它,但在这种情况下,一个具有 x 值的不可见点会触发它。

      我认为在这里使用连续轴更自然。在这种情况下,我使用我在这里找到的技巧使 x 轴的标签在文本值和空白之间交替:https://stackoverflow.com/a/25961969/6851825 它将c("uno", "tres") 变成c("uno", "", "tres", "")

      nums <- c("uno", "tres", "cinco", "siete", "nueve")
      ggplot() +
        ggtitle("Grafico variado") +
        theme_classic() +
        theme(plot.title = element_text(size = 10)) +
        scale_y_continuous(breaks = 1:10, name = NULL) +
        scale_x_continuous(breaks = 1:10, name = NULL,
                           labels = c(rbind(nums, ""))) +
        coord_cartesian(xlim = c(0,11), ylim = c(0,10), expand = 0) +
        geom_hline(yintercept = 5, linetype = "dotted") +
        annotate("point", x = 5, y = 0, alpha = 0)
      

      【讨论】:

      • 首先,感谢第一个解决方案。为我的目的工作。现在,我得到一个“找不到对象'nums'”。我错过了什么?
      • 糟糕,我好像忘记粘贴那行了。已在上面添加。
      猜你喜欢
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      相关资源
      最近更新 更多