如何在ggplot中仅反转第二y轴?

时间:2020-05-11 16:24:23

标签: r ggplot2 plot bar-chart yaxis

我的绘图几乎已经准备好,我只是无法反转在闪避小节线上绘制的直线(geom_line)的辅助轴。到目前为止,我的代码:

coeff<--1/50
ggplot(coll,aes(Date,value,fill=variable))+
  geom_bar(stat="identity",position="dodge")+
  ylab("Precipitation")+xlab("Month")+ylim(0,900)+
  geom_line(aes(x=Date,y=Temp/coeff,col="black"),col="black")+
  geom_point(aes(x=Date,y=Temp/coeff,col="black"),col="black")+
  scale_y_continuous(sec.axis = sec_axis(~.*coeff, name = "Temp"))

我只需要将右边的(yemp)的y轴反转,并从零开始从0到-15的顶部开始

这是我现在This is the result I have for now

的结果

我的数据框看起来像这样:

Date<-c("1/1/2019","2/1/2019","3/1/2019","4/1/2019","5/1/2019","6/1/2019","7/1/2019",
        "8/1/2019","9/1/2019","10/1/2019","11/1/2019","12/1/2019")%>%data.frame()
names(Date)[names(Date) == "."] <- "Date"
Date<-as.POSIXct(Date$Date,format="%m/%d/%Y")
Month<-c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")%>%data.frame()
names(Month)[names(Month) == "."] <- "Month"
Temp<-c(NA,-3,-6,-13,-12,-6,-5,-1,-4,-7,-8,NA)%>%data.frame()
names(Temp)[names(Temp) == "."] <- "Temp"
variable<-c(rep("bar1",12,sep=","),rep("bar2",12,sep=","),rep("bar3",12,sep=","))%>%data.frame()
names(variable)[names(variable) == "."] <- "variable"
value<-rnorm(36,400,100)
coll<-cbind(Date,Month,Temp,variable,value)

1 个答案:

答案 0 :(得分:0)

您的系数真的是您想要的吗?

-3 / -(1/50) = 150,而-6 / -(1/50) = 300则意味着较低的温度在您的图表上显示较高

所以我调整了数据以使其直观地工作。

但是,您应该真正意识到,将两个不同比例的y轴视为好习惯。

有关此问题的详细讨论,请参见以下链接:ggplot with 2 y axes on each side and different scales

说了这么多,到此为止。我整理了您的数据框:希望您可以看到这可能是一种更简单的方法。


# packages

library(ggplot2)

# data

coll <- data.frame(
  Date = c("1/1/2019", "2/1/2019", "3/1/2019", "4/1/2019", "5/1/2019", "6/1/2019", "7/1/2019",
        "8/1/2019", "9/1/2019", "10/1/2019", "11/1/2019", "12/1/2019"),
  Month = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"),
  Temp = c(NA,-3,-6,-13,-12,-6,-5,-1,-4,-7,-8,NA), 
  variable = c(rep("bar1", 12, sep = ","), rep("bar2", 12, sep = ","), rep("bar3" , 12, sep = ",")),
  value = rnorm(36,400,100))

# Data wrangling

coll$Date <- as.POSIXct(coll$Date, format = "%m/%d/%Y")

# Create additional variable for modified temperature to scale with the preciptation y axis
# tranformation coefficient
coeff <- 50

coll$temp_mod <- (coll$Temp * coeff) + 700





# plot

ggplot(coll, aes(Date, value, fill = variable))+
  geom_bar(stat = "identity", position = "dodge")+
  ylab("Precipitation")+
  xlab("Month")+
  ylim(0, 900)+
  geom_line(aes(Date, temp_mod))+
  geom_point(aes(Date, temp_mod))+
  scale_y_continuous(sec.axis = sec_axis(~-rev(.) / coeff, name = "Temp", breaks = seq(0, -15, by = -2)))

enter image description here

相关问题