ggplot双反转y轴和geom_hline拦截计算

时间:2018-01-23 02:49:06

标签: r ggplot2

我在ggplot2中创建了一个带有两个y轴的折线图,并且只想在反转轴上绘制一个数据集(蓝色),并希望其他数据集(红色)绘制在与第一个不同的比例上。但是,我正在使用的代码反转两个轴,虽然第二个y轴已编码为具有不同的比例,但第二个数据集(红色)正在使用第一个y轴的比例绘制。此外,我创建了一条线(绿色),我必须确定蓝线拦截它的位置。我知道这个问题的后半部分之前已经被问过并得到了回答,但是在该帖子中已经注意到该解决方案实际上并不起作用。任何输入都会有所帮助!谢谢!我提供了一个样本数据集,因为我的数据集太大而无法重新创建。




  time< -c(1,2,3,4,5,6, 7,8,9,10)
高度< -C(100,330,410,570,200,270,230,390,400,420)
温度< -C(37,33,14,12,35,34,32,28,26,24)&# xA; tempdf< -data.frame(time,height,temp)

 makeplot< -ggplot(tempdf,aes(x = time))+ geom_line(aes(y = height),color =“蓝色“)
 + geom_line(aes(y = temp),color =“Red”)+
 scale_y_continuous(sec.axis = sec_axis(〜。/ 100,name =
“Temperature”),trans =“reverse”)+
 geom_hline(aes(yintercept = 250),color =“green”)
  







3 个答案:

答案 0 :(得分:3)

ggplot只会进行1:1轴变换,如果它翻转一个轴,则会翻转两个轴,所以你需要找出一个方程来平移你的轴。乘以(或除以)负值会将温度轴翻转回标准增量刻度。这两个方程用于获得相同比例的样本数据。

height = temp*(-10) + 600
temp = (height - 600)/(-10)

现在,您可以将方程式合并到绘图代码中,第一个将温度数据转换为适合高度尺度的数字,第二个将次轴数转换为显示温度的刻度。

makeplot<-ggplot(tempdf,aes(x=time)) + 
  geom_line(aes(y=height),color="blue") + 
  geom_line(aes(y = (temp*(-10)) + 600), color="red")+
  scale_y_continuous(sec.axis=sec_axis(~(.-600)/(-10),name = 
                                     "Temperature"),trans="reverse")+
  geom_hline(aes(yintercept=250), color="green")
makeplot

enter image description here

答案 1 :(得分:1)

暂时忽略线路问题,这里有两种双轴替代方案。第一,方面:

library(tidyverse)
library(scales)
tempdf %>% 
  # convert height to depth
  mutate(height = -height) %>% 
  rename(depth = height) %>% 
  gather(key, value, -time) %>% 
  ggplot(aes(time, value)) + 
    geom_line() + 
    facet_grid(key ~ ., scales = "free_y") + 
    scale_x_continuous(breaks = pretty_breaks()) +
    theme_bw()

enter image description here

其次,使用有色点来指示每个深度的温度:

tempdf %>% 
  mutate(height = -height) %>% 
  rename(depth = height) %>% 
  ggplot(aes(time, depth)) + 
    geom_line() + 
    geom_point(aes(color = temp), size = 3) + 
    geom_hline(yintercept = -250, color = "blue") +
    scale_color_gradient2(midpoint = 25, 
                          low = "blue", 
                          mid = "yellow", 
                          high = "red") + 
    scale_x_continuous(breaks = pretty_breaks()) + 
    theme_dark()

enter image description here

答案 2 :(得分:0)

另一种选择是路径图:

ggplot(tempdf, aes(height, temp)) + 
  geom_path() + 
  geom_point(aes(fill = time), size = 8, shape = 21) + 
  geom_text(aes(label = time)) + 
  viridis::scale_fill_viridis()

enter image description here