简体   繁体   中英

How to graph two variables on a timeline axis in R?

I have a df:

Date      Events    Percentage
01/2020     200      5.5
02/2020     190      6.3
03/2020     8000     28.3
04/2020     12000    30.1
05/2020     15000    27.6
06/2020     13000    16.7
07/2020     10000    12.0
08/2020     11000    17.0
09/2020     18000    20.1
10/2020     15000    22.2
11/2020     16000    25.1
12/2020     18000    29.0

I would like to plot these on a graph where the X-axis is the Months and the Y-axis has 2 variables, the total events, and the percentage. Such as:

![This Graph]( 在此处输入图像描述 https://imgur.com/a/yJ1WZkr )

You can write a function for transformation of secondary axis and use it in plotting.

library(tidyverse)

adjust_sec_Axis <- function(x, y) {
  a <- min(x)
  b <- max(x)
  (((b-a) * (y - min(y)))/diff(range(y))) + a
}

df %>%
  mutate(Percentage = adjust_sec_Axis(Events, Percentage)) %>%
  pivot_longer(cols = -Date) %>%
  ggplot(aes(Date, value, fill = name, group = name,linetype = name)) + 
  geom_line() + 
  scale_y_continuous(sec.axis = sec_axis(~{
    adjust_sec_Axis(df$Percentage, .)
  }))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM