如何使用ggplot2将轴标签保持在一侧,将轴标题保持在另一侧

问题描述 投票:1回答:1

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

r ggplot2 plot label axis
1个回答
3
投票

您可以在sec.axis = dup_axis()中使用scale_x_*()复制两个轴,然后删除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())

enter image description here


其他示例和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

© www.soinside.com 2019 - 2024. All rights reserved.