【问题标题】:Remove extra space beyond xlim and ylim [duplicate]删除 xlim 和 ylim 之外的额外空间 [重复]
【发布时间】:2014-05-17 11:38:24
【问题描述】:

我想制作一个密度图,以便轴紧邻(或至少非常靠近)刻度线。从这个 MWE 中可以看出,ggplot2 在 x 轴和 y 轴的刻度线和轴之间保留了一些空间,即使我指定了 xlimylim。如何删除它们?

对于其他类型的绘图,您似乎可以调用 scale_y_continuous(limits=c(0, 100), expand = c(0, 0)) (for example) 之类的东西,但使用这些参数调用 scale_linetype_manual() 似乎没有任何作用。

另请注意,在此处的注释中,我使用geom_segment 绘制轴。有没有更好的方法来做到这一点?

set.seed(0)
the.df <- data.frame( x = rnorm(800, 50, 10), group = rep(letters[1:8], each = 100))

p <- ggplot(the.df) + 
    stat_density(aes(x = x, linetype = group), geom = "line", position = "identity") +
    xlim(10, 90) + ylim(0, 0.06) +
    scale_linetype_manual(values = c("11", "12", "13", "14", "21", "22", "23", "24")) +
    geom_segment(aes(x = 10, y = 0, xend = 90, yend = 0)) +
    geom_segment(aes(x = 10, y = 0, xend = 10, yend = 0.06))

p

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    原来scale_x_continuous()scale_x_continuous 确实有效。我只是没有正确使用它们。

    set.seed(0)
    the.df <- data.frame( x = rnorm(800, 50, 10), group = rep(letters[1:8], each = 100))
    
    p <- ggplot(the.df) + 
        stat_density(aes(x = x, linetype = group), geom = "line", position = "identity") +
        scale_linetype_manual(values = c("11", "12", "13", "14", "21", "22", "23", "24")) +
        scale_x_continuous(limits=c(10, 90), expand = c(0, 0)) +
        scale_y_continuous(limits=c(0, 0.06), expand = c(0, 0)) +
        geom_segment(aes(x = 10, y = 0, xend = 90, yend = 0)) +
        geom_segment(aes(x = 10, y = 0, xend = 10, yend = 0.06))
    
    p
    

    【讨论】:

      【解决方案2】:

      另一个使用coord_cartesian 代替连续位置刻度(x & y)的选项:

      set.seed(0)
      the.df <- data.frame( x = rnorm(800, 50, 10), group = rep(letters[1:8], each = 100))
      p <- ggplot(the.df) + 
        stat_density(aes(x = x, linetype = group), geom = "line", position = "identity") +
        scale_linetype_manual(values = c("11", "12", "13", "14", "21", "22", "23", "24")) +
        geom_segment(aes(x = 10, y = 0, xend = 90, yend = 0)) +
        geom_segment(aes(x = 10, y = 0, xend = 10, yend = 0.06))+
        coord_cartesian(xlim = c(10, 90), ylim = c(0, .06), expand = FALSE)
      p
      

      【讨论】:

      • 请注意,现在您需要将 expand = FALSE 添加到 coord_cartesian。
      • @machow 注意到并更改了它。我认为这种行为在其中一个版本中发生了变化。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2020-10-16
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 2013-01-09
      • 1970-01-01
      • 2013-08-21
      相关资源
      最近更新 更多