我想制作一个密度图,使轴与刻度线相邻(或至少非常接近)。如本MWE所示,即使我指定了ggplot2
和xlim
,ylim
也会在刻度线和x轴和y轴上的轴之间保留一些空格。我该如何删除它们?
使用其他类型的图表,您似乎可以调用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
答案 0 :(得分:16)
结果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
答案 1 :(得分:3)
使用coord_cartesian
代替连续位置比例(x&amp; 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))
p