在 R ggplot 中构建辅助轴

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

我需要在一张图表上生成两条线。一个变量 - T 被绘制为主轴,我希望为变量 ZP 创建一个辅助轴。

数据框如下:

粒子效果

广告 RT ZP
0 20 -34
1 12 -30
2 10 -27
3 8 -25
4 6 -20
5 4 -12
6 2 -6
7 1 -2

我正在尝试将主 Y 轴中 T 变量的范围设置为从 0 到 75,将 ZP 的辅助 Y 轴设置为从 -50 到 0。我使用 sec.axis 函数尝试过的所有操作都发生了变化两个 Y 轴范围。我可能遇到了错误,但无法识别它。我将不胜感激的帮助!

particle_effect %>%
  
  ggplot(aes(x = AD)+
  geom_point(aes(y=TR),size = 2, alpha = 0.75)+
  geom_point(aes(y=zp),size = 2, alpha = 0.75)+
  geom_line(aes(y=TR))+
  geom_line(aes(y=zp))+
  scale_y_continuous(name = "T", 
                     sec.axis = sec_axis(~.,name = "ZP"))+
  theme_bw()
r ggplot2 plot
1个回答
0
投票

这种表述可能很难正确解释,并可能导致不恰当的结论。不过,仍然可以用

ggplot2
来构建。次轴是主轴的变换,为了实现此目的,您需要在绘图之前调整第二轴上的值。下面我设置了
ZP = ZP + 50
并在创建
sec_axis
时减去 50。

此图给人的印象是两个系列在 AD=0 和 AD=1 之间交叉,尽管它们在 AD=7 时最接近。

library(ggplot2)
library(dplyr)
library(tidyr)

particle_effect |>
  mutate(ZP = ZP + 50) |>
  pivot_longer(-AD) |>
  ggplot(aes(x = AD, y = value, group = name, color = name)) +
  geom_point(size = 2, alpha = 0.75) +
  geom_line() +
  scale_y_continuous(name = 'T',sec.axis = sec_axis(~.-50, name = 'ZP', breaks = seq(0,-50,-10))) +
  theme_bw() +
  labs(color = '') +
  theme(legend.position = 'top')

创建于 2024-05-06,使用 reprex v2.1.0

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