如何使用ggplot2将坐标轴标签保持在一侧而将坐标轴标题放在另一侧?

4

我想知道是否可能将绘图的坐标轴标签保留在绘图的一侧,而将绘图的坐标轴标题保留在另一侧,具体来说,在离散的geom_tile()绘图中如下所示: change axis title to other position

1个回答

5

您可以在scale_x_*()内部使用sec.axis = dup_axis()来复制两个轴,然后在theme()内删除不需要的内容。

ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point() +
  labs(title="mpg vs hp") +
  scale_y_continuous(position = 'right', sec.axis = dup_axis()) + 
#remember to check this with the proper format
  scale_x_continuous(position = "top", sec.axis = dup_axis()) +
  theme(plot.title = element_text(hjust=0.5),
        axis.text.x.top = element_blank(), # remove ticks/text on labels
        axis.ticks.x.top = element_blank(),
        axis.text.y.right = element_blank(),
        axis.ticks.y.right = element_blank(),
        axis.title.x.bottom = element_blank(), # remove titles
        axis.title.y.left = element_blank())

在这里输入图片描述


另一个例子,使用theme_new()函数:

theme_new <- function() {
  theme(plot.title = element_text(hjust=0.5),
        axis.text.x.top = element_blank(), # remove ticks/text on labels
        axis.ticks.x.top = element_blank(),
        axis.text.y.right = element_blank(),
        axis.ticks.y.right = element_blank(),
        axis.title.x.bottom = element_blank(), # remove titles
        axis.title.y.left = element_blank())
}

ggplot(df, aes(x, y)) +
  geom_tile(aes(fill = z), colour = "grey50") +
  labs(title="some title") +
  scale_y_continuous(position = 'right', sec.axis = dup_axis()) + 
  scale_x_continuous(position = "top", sec.axis = dup_axis()) +
  theme_new()

enter image description here


非常棒的回答@RLave,感谢您的时间和帮助!但它们是离散变量,而不是连续变量。因此我得到了“Error: Discrete value supplied to continuous scale”错误。另一方面,使用“scale_x_discrete”,我得到了“unused argument (sec.axis = dup_axis())”错误。 - Bernardo
1
@Bernardo 这里有一个使用 discrete 的解决方法 https://dev59.com/41cO5IYBdhLWcg3wtzxg。 - RLave
1
你需要强制使用 as.numeric(),然后就可以使用 scale_*_continuos() 进行操作了。 - RLave

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