在ggplot中拟合双Y轴(barplot [SPI函数]-lineplot [crop Yield])

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

我想用我的SPI函数和马铃薯产量创建一个双图,以查看它们之间的关系。我只是尝试这样做,但“ y”值彼此不匹配

这里的产量数据 enter link description here

此处有SPI_data enter link description here

library(ggplot2)
library(tidyverse)

anhos <- paste(c(1965:2018), "12", "01", sep = "-")
reemp <- paste(c(1965:2018), "01", "01", sep = "-")

yield_dt <- fread(rendi_MINAGRI.txt, header = T)
spei <- fread("ho_000253.txt", header = T)
spei <- spei[spei$YEAR %in% anhos]
spei$YEAR <- as.data.table(reemp)
spei$YEAR <- as.Date(spei$YEAR)              
DF <- spei %>% dplyr::mutate(sign = ifelse(SPEI >= 0, "pos", "neg"))
DF$Rendi <- dt_rendi[,c("ANCASH")]/1000            
pl <- ggplot(data = DF, mapping = aes(x = YEAR, y = Rendi, group = 1)) + 
          geom_line(aes(color="Rendimiento")) +
          geom_point(aes(color="Rendimiento"))
pl <- pl + geom_bar(aes(y = SPEI, col = sign, fill = sign), show.legend = F, stat = "identity")+
       scale_color_manual(values = c("Rendimiento" = "green", "pos" = "darkblue", "neg" ="red"))+
       scale_fill_manual(values = c("Rendimiento" = "green" ,"pos"  = "darkblue", "neg" = "red"))          
pl <- pl + scale_y_continuous("Rendimiento Papa [tn/ha]",sec.axis = sec_axis(~., name =
      toupper(indx))) +
      scale_x_date(date_breaks = "2 years", date_labels = "%Y ", expand = c(0,0))
png(filename =  paste0("SPEI",".png"), width = 2800, height = 1200, units = "px", pointsize = 9,res = 250 )
print(pl)

最后,我有类似enter link description here的东西,并且您可以看到我需要在两个轴上都适合的东西进行比较,因此我不需要在左右轴上都使用相同的标签。我希望有人能帮助我。

谢谢。

enter image description here

r ggplot2 plot spi yaxis
1个回答
0
投票

感谢您没有答复,但最后我希望这个小答案可以帮助某人..像我这样的新手……这是我在ggplot部分所做的。

ggplot(DF) + 
        geom_line(aes(x=YEAR, y=((Rendi+5)/2.5)-5)) +            
        geom_bar(aes(x=YEAR, y=SPEI, col=sign, fill = sign) , show.legend = F,stat = "identity", alpha = 0.2) +
        geom_label(data = DF, aes(x = YEAR, y = ((Rendi+5)/2.5)-5, label = sprintf('%.1f', Rendi)), 
                   vjust = 0.8, size = 1.3, alpha = 0.7, position = "dodge") +
        scale_color_manual(values = c("Rendimiento" = "green", "pos" = "darkblue", "neg" = "red")) +
        scale_fill_manual(values = c("Rendimiento" = "green" ,"pos"  = "darkblue", "neg" = "red")) +
        scale_y_continuous(
          name = "SPEI\n", sec.axis = sec_axis(~ ((.+5)*2.5)-5, name = "Rendimiento Papa [tn/ha]\n"),
          limits = c(-5, 5)
        )

我知道了

SPI index join with potato Yield

不客气。

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