Creating Graph With Multiple Axis

I am looking to create a graph where I can show multiple trends over a date format. The bottom X-Axis being date say Jan - Jun, on the left I want to have a data set in a bar graph and the right axis showing a line plot. Where can I find an example on how to create this perhaps using ggplot?

There is a sec_axis function in ggplot with which you can define a y axis on the right. Notice that the scale of the second y axis must be a transformation of the primary axis. Will that work for you?

in plotly you make a bar chart, then add a trace ( a line) and set the layout to be on the right axis)

library(tidyverse)
library(plotly)

set.seed(42)
(df <- tibble(
  date_x = seq.Date(from=as.Date("2019-01-01"),
                  by = "1 month",
                  length.out = 12),
  barheight_y1 = sample.int(n = 100,size=12),
  lineheight_y2 = runif(12)
))
  
(p <- plot_ly(data=df,
             x=~date_x,
             y=~barheight_y1,
             type="bar",
             name="mybar"
             ) %>% add_trace(
               type="scatter",
               mode="lines+markers",
               y=~lineheight_y2,
               name="myline",
               yaxis="y2"
             ) %>%
    layout(yaxis=list(side="left",title="barheight"),
           yaxis2=list(side="right",title="lineheight",overlaying='y')))

image

Here is a ggplot example.

library(ggplot2)
DF <- data.frame(Date = lubridate::ymd(c("2020-01-01", "2020_02-01", "2020-03-01")),
                 Var1 = c(4,7,6),
                 Var2 = c(33, 68, 45))
ggplot(DF, aes(Date)) +
  geom_col(mapping =aes( y = Var1), fill = "skyblue") +
  geom_line(mapping = aes(y = Var2/10), color = "red") + #scale value sown by*10
  scale_y_continuous(sec.axis = sec_axis(~. * 10, #scale labels up by *10
                                         name = "Second Variable")) +
  labs(y = "First Variable") +
  theme(axis.title.y.right = element_text(color = "red"))

Created on 2020-06-25 by the reprex package (v0.3.0)

Perfect, this was exactly what I was looking for.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.