ggplot with two y-axis in R?

跟風遠走 提交于 2021-02-08 12:11:40

问题


I have asked this question earlier but someone close it indicating that it has answer. I am pretty confuse how i can get the two variables plotted on two Y-axis. I want to plot Level on the left y-axis and Flow on the right y-axis (ie., secondary axis). Here is my data and i would appreciate a response.

library(tidyverse)
library(lubridate)

set.seed(1500)

FakeData <- data.frame(Date = seq(as.Date("2020-01-01"), to = as.Date("2020-01-31"), by = "days"),
                       Level = runif(31, 0, 30), Flow = runif(31, 1,10))
ggplot(data = FakeData, aes(x = Date))+
  geom(aes(y = Level))

Here is an example output of the plot i would like to see


回答1:


Here is a start:

FakeData <- data.frame(Date = seq(as.Date("2020-01-01"), to = as.Date("2020-01-31"), by = "days"),
                       Level = runif(31, 0, 30), Flow = runif(31, 1,10))

scale_factor <- 4
   ggplot(data = FakeData, aes(x = Date))+
   geom_col(aes(y = Level), fill="darkgreen") +
   geom_line(aes(y = Flow*scale_factor), color="blue") +
   scale_y_continuous(sec.axis = sec_axis(~ .*1, labels = number_format(scale=1/scale_factor), name="Flow"))



来源:https://stackoverflow.com/questions/62579357/ggplot-with-two-y-axis-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!