如何在 ggplot 中仅反转次要 y 轴?

How to reverse only secondary y axis in ggplot?

我的情节几乎准备好了,我只是无法反转在闪避条形图上绘制的线 (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"))

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

这是我现在的结果

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

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)

你的系数真的如你所愿吗?

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

所以我调整了数据,使这项工作直观。

然而,您真的应该意识到,两个 y-axis 具有不同的尺度并不是好的做法。

请参阅此 link 以获得对该问题的良好讨论: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)))