I am trying to stack two graphs of separate styles into one with ggplot2. I can get the to graphs fine when I do them separately. But when I try to group them I can’t get the sec.axis to come out correctly.
data
Delivery.Count <- c(382,12331,438,27375,6180,5329,3666,11324,9602,212,6851,10874,590,1527)
Cumulative.Percent <- c(0.38,12.78,13.22,40.73,46.94,52.29,55.98,67.36,77.01,77.22,84.11,95.04,95.63,97.16)
Delivery.Date <- c("Friday, September 9, 2022","Saturday, September 10, 2022","Sunday, September 11, 2022","Monday, September 12, 2022","Tuesday, September 13, 2022","Wednesday, September 14, 2022","Thursday, September 15, 2022","Friday, September 16, 2022","Saturday, September 17, 2022","Sunday, September 18, 2022","Monday, September 19, 2022","Tuesday, September 20, 2022","Wednesday, September 21, 2022","Thursday, September 22, 2022")
Cumulative.Total <- c(382,12713,13151,40526,46706,52035,55701,67025,76627,76839,83690,94564,95154,96681)
dataset <- data.frame(Delivery.Count,Cumulative.Percent,Delivery.Date,Cumulative.Total)
dataset$Delivery.Date <- as.Date(dataset$Delivery.Date,format="%A, %B %d, %Y")
plot 1
library(ggplot2)
ggplot(dataset) +
geom_bar(aes(x=Delivery.Date,y=Delivery.Count),fill="#00FFFF",stat="identity")
plot 2
ggplot(dataset) +
geom_line(aes(x=Delivery.Date,y=Cumulative.Percent),color="red")
But then when i try to combine them
ggplot(dataset) +
geom_bar(aes(x=Delivery.Date,y=Delivery.Count),fill="#00FFFF",stat="identity") +
geom_line(aes(x=Delivery.Date,y=Cumulative.Percent),color="red",group=1)
The line of the second graph stays along the bottom. And when I try to add in the scale_y_continuous, I get the error about cannot give a NULL trans. I’m not sure how to combine these like how would be done on a line and stack column chart on PowerBI. I need the column max to be the range of the sec.axis.
>Solution :
Because secondary axes with different variables can very easily be misinterpreted, support is limited. But you can calculate your own conversion factor to get similar scales. For example:
my_factor <- 300
ggplot(dataset, aes(Delivery.Date)) +
geom_col(aes(y = Delivery.Count), fill="#00FFFF") +
geom_line(aes(y = Cumulative.Percent * my_factor), color="red") +
scale_y_continuous(
sec.axis = sec_axis(trans = \(x) x / my_factor, name = 'Cumulative percent'),
expand = expansion(c(0, 0.05))
)
300 comes out nice here, but you can also just calculate the conversion factor, i.e.
my_factor <- with(dataset, max(Delivery.Count) / max(Cumulative.Percent))
