【问题标题】:ggplot: change left and right axis rangesggplot:更改左右轴范围
【发布时间】:2021-10-29 14:40:26
【问题描述】:

我需要使用ggplot 绘制两个散点图。一种是所有值在 (0,0.02) 之间的正数,另一种是所有值在 (0,-1500) 之间的负数。我尝试使用sec_axis 来传达不同的比例,但我已经能够产生以下内容。

这是使用

制作的
library(tidyverse)
library(ggplot2)
scl = with(use_deciles, max(abs(coef_navy))/max(abs(coef_maroon)))

ggplot(use_deciles) + 
  geom_point(aes(x = decile_navy, y = coef_navy, color = 'navy')) + 
  geom_point(aes(x = decile_maroon, y = coef_maroon*scl, color = 'maroon')) +    
  labs(x = "Group", y = "") +
  scale_color_manual(values = c('maroon', 'navy')) + 
  scale_y_continuous(sec.axis = sec_axis(~. /scl, name = "2nd axis"))

如您所见,scl 提供了左右轴之间的最佳重新缩放,但这是我的问题:

如何调整 y 轴的范围,以便我可以将 0 放在左轴的顶部但在右轴的底部?

鉴于我只能将sec_axis 定义为左轴的线性变换,我不确定此选项是否真的可以移动标签。如果我需要手动重新标记 y 轴,那可以,但我想先了解如何在此处叠加散点图。

提前谢谢你。

【问题讨论】:

标签: r ggplot2 axis-labels axes scatter


【解决方案1】:

如果我正确理解您的问题,我认为不更改值是不可能的。我认为您不能在不影响右轴的情况下更改左轴的限制,而且我不相信您可以独立更改每个轴的标签。

一种可能的替代方法是使用facet_wrap() 函数将它们绘制在彼此之上,例如

library(tidyverse)

# Create example data
use_deciles <- data.frame(count = 1:10,
                          coef_maroon = c(0.005, 0.01, 0.015, 0.02, 0.03, 0.07, 0.09, 0.12, 0.15, 0.2),
                          coef_navy= c(0, -200, -400, -600, -800, -700, -900, -900, -1100, -1200))

# Original method
scl = with(use_deciles, max(abs(coef_navy))/max(abs(coef_maroon)))

ggplot(use_deciles) + 
  geom_point(aes(x = count, y = coef_navy, color = 'navy')) + 
  geom_point(aes(x = count, y = coef_maroon*scl, color = 'maroon')) +    
  labs(x = "Group", y = "") +
  scale_color_manual(values = c('maroon', 'navy')) + 
  scale_y_continuous(sec.axis = sec_axis(~. /scl, name = "2nd axis"))

# Facet_wrap method (on top of each other)
use_deciles %>% 
  pivot_longer(-count) %>%
  ggplot(aes(x = count, y = value, colour = name)) +
  geom_point() +
  scale_color_manual(values = c('maroon', 'navy')) +
  facet_wrap(~name, scales = "free_y", ncol = 1)

reprex package (v2.0.1) 于 2021-08-31 创建

【讨论】:

    【解决方案2】:

    用@jared_mamrot 数据尝试这样的事情:

    ggplot(use_deciles) + 
      geom_point(aes(x = count, y = coef_navy, color = 'navy')) + 
      geom_point(aes(x = count, y = coef_maroon*scl-1200, color = 'maroon')) +    
      labs(x = "Group", y = "") +
      scale_color_manual(values = c('maroon', 'navy')) + 
      scale_y_continuous(sec.axis = sec_axis(~(.+1200)/scl, name = "2nd axis"))
    

    你会得到这个:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      相关资源
      最近更新 更多