首页 > 解决方案 > 添加第二个轴(sec.axis)时ggplot图发生变化

问题描述

我正在尝试创建一个带有两个 y 轴的图,每个轴都有不同的值。当我添加第二个轴的数据时,第一个轴得到额外的(不需要的)区域。知道如何解决这个问题吗?我创建了一些简单的示例,只是为了说明我做错了什么。

谢谢!

    library(tidyverse)
starwars <- starwars[,c(2,3,7)] %>% drop_na() %>% 
  dplyr::filter(mass > 40 & mass < 200) %>%
  mutate(some_y = height/max(height))

viz <- starwars %>% ggplot() +
  geom_line(aes(x = birth_year, y = mass), colour = "blue") + 
  labs(ylim = c(70,150))  #until here, the plot is fine

viz +
  geom_line(data = starwars,   #starting from here, it jumps up
            aes(x = birth_year, y = some_y*100), colour = "red") +
  scale_y_continuous(sec.axis = sec_axis(~ ., name = "2nd y",
                labels = seq(0, 100, length.out = 11), breaks = seq(0, 100, length.out = 11)))

首先,它工作正常:(即)

即

然后,它跳起来:(即+ ...)

看看左轴是如何从 30 开始的

标签: rggplot2axis

解决方案


推荐阅读