在facet_wrap中为每个图添加刻度标记的ggplot

10
我想在facet_wraps的上方行中显示绘图的x轴刻度。例如:
library(ggplot2)
ggplot(diamonds, aes(carat)) +  facet_wrap(~ cut, scales = "fixed") +  geom_density()

生成这个图:

Actual Plot

我想在这个图上添加如下所示的刻度线:

Desired Plot

有没有一种简单的方法可以实现这个结果?

1个回答

16

使用scales = "free_x"会为每个图形添加x轴:

ggplot(diamonds, aes(carat)) + 
    geom_density() + 
    facet_wrap(~cut, scales = "free_x")

带有x轴的图

然而,正如您所见和语法所示,它还可以自动调整每个图的限制,因此如果您希望它们都保持一致,则需要使用 xlimlimsscale_x_continuous 进行设置:

ggplot(diamonds, aes(carat)) + 
    geom_density() + 
    xlim(range(diamonds$carat)) + 
    # or lims(x = range(diamonds$carat))    
    # or scale_x_continuous(limits = range(diamonds$carat))
    facet_wrap(~cut, scales = "free_x")

具有统一x轴的图形


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接