带有秒轴的ggplot的Y限制

我需要使用sec.axis创建一个Dual-y图,但是无法使两个轴正确缩放。

我一直在遵循此线程中的说明:ggplot with 2 y axes on each side and different scales

但是每次我将ylim.prim的下限更改为0以外的任何值时,都会弄乱整个情节。出于可视化的原因,我需要两个轴的特定y限制。另外,当我将geom_col更改为geom_line时,它也弄乱了辅助轴的限制。

climate <- tibble(
  Month = 1:12,Temp = c(23,23,24,23),Precip = c(101,105,100,101,102,112,121,107,114,108,120)
  )

ylim.prim <- c(0,125)   # in this example,precipitation
ylim.sec <- c(15,30)    # in this example,temperature

b <- diff(ylim.prim)/diff(ylim.sec)
a <- b*(ylim.prim[1] - ylim.sec[1])

ggplot(climate,aes(Month,Precip)) +
  geom_col() +
  geom_line(aes(y = a + Temp*b),color = "red") +
  scale_y_continuous("Precipitation",sec.axis = sec_axis(~ (. - a)/b,name = "Temperature"),) +
  scale_x_continuous("Month",breaks = 1:12)  

带有秒轴的ggplot的Y限制

ylim.prim <- c(0,Precip)) +
  geom_line() +
  geom_line(aes(y = a + Temp*b),breaks = 1:12)  

带有秒轴的ggplot的Y限制

ylim.prim <- c(95,breaks = 1:12)  

带有秒轴的ggplot的Y限制

huangxi500 回答:带有秒轴的ggplot的Y限制

如何?

  ggplot(climate,aes(Month,Precip)) +
    geom_line() +
    geom_line(aes(y = 4.626*Temp),color = "red") +
    scale_y_continuous("Precipitation",sec.axis = sec_axis(~ ./4.626,name = "Temperature"),) +
    scale_x_continuous("Month",breaks = 1:12)   

如果您需要进一步说明,请告诉我。 enter image description here

,

根据我在代码中看到的,两个标度之间的转换有点太简单了。

为了获得我认为您想要的结果,有必要对温度数据进行归一化(通过这种方式,您可以改变散度和均值,使其适合您的主要y尺度),然后计算y轴的反向归一化。

通过归一化,我的意思是:(Temp - mean(TEMP))/sd(TEMP),其中TEMP是所有值的数组,而Temp是要绘制的特定值。结果与之相乘的附加scalingfactor允许您更改绘制数据相对于主要y轴的分布。 y轴偏移(此处为a)需要根据数据的传播范围进行调整,并且仅应在所有其他步骤之后添加。

要将次级y轴比例调整回您的值,只需反过来执行计算中的每个步骤即可。

这样,您就可以在两个时间序列上实现漂亮且可调整的叠加:

ylim.prim <- c(95,125)   # in this example,precipitation
ylim.sec <- c(15,30)    # in this example,temperature

a <- ylim.prim[1] + 10 #needs to be adjusted for nice fit
scalingfactor <- 5 #to vary the spread

TEMP <- climate$Temp #needed for coherent normalisation

ggplot(climate,Precip)) +
  geom_line() + ylim(ylim.prim) +
  geom_line(aes(y = (a + ((Temp - mean(TEMP))/sd(TEMP)) *scalingfactor) ),color = "red") +
  scale_y_continuous("Precipitation",sec.axis = sec_axis(~ (. - a) / scalingfactor * sd(TEMP) +mean(TEMP),) +
  scale_x_continuous("Month",breaks = 1:12) 

我尚不能发布图片(由于声誉),但是请检查下面的链接以获取结果: 行:plot of Temperature vs Precipitation over time

本文链接:https://www.f2er.com/3134724.html

大家都在问