删除超出xlim和ylim的额外空间

cei*_*cat 19 r ggplot2

我想制作一个密度图,使轴与刻度线相邻(或至少非常接近).如本MWE所示,ggplot2即使我指定了xlim和,也保留了刻度线和x轴和y轴上的轴之间的一些空间ylim.我该如何删除它们?

对于其他类型的图,看起来你可以调用类似的东西scale_y_continuous(limits=c(0, 100), expand = c(0, 0))(例如),但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
Run Code Online (Sandbox Code Playgroud)

cei*_*cat 17

结果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
Run Code Online (Sandbox Code Playgroud)


mpa*_*nco 5

使用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
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明