0

I'm trying to plot a line graph (data points between 0 and 2.5, with interval of 0.5). I want to plot some bars in the same chart on the right-hand axis (between 0 and 60 with interval of 10). I am making some mistake in my code such that the bars get plotted in the left hand axis.

Here's some sample data and code:

Month <- c("J","F","M","A")
Line <- c(2.5,2,0.5,3.4)
Bar <- c(30,33,21,40)
df <- data.frame(Month,Line,Bar)

ggplot(df, aes(x=Month)) +
  geom_line(aes(y = Line,group = 1)) +
  geom_col(aes(y=Bar))+
  scale_y_continuous("Line",
                     sec.axis = sec_axis(trans= ~. /50, name = "Bar"))

Here's the output

Thanks in advance.

1 Answer 1

1

Try this approach with scaling factor. It is better if you work with a scaling factor between your variables and then you use it for the second y-axis. I have made slight changes to your code:

library(tidyverse)
#Data
Month <- c("J","F","M","A")
Line <- c(2.5,2,0.5,3.4)
Bar <- c(30,33,21,40)
df <- data.frame(Month,Line,Bar)
#Scale factor
sfactor <- max(df$Line)/max(df$Bar)
#Plot
ggplot(df, aes(x=Month)) +
  geom_line(aes(y = Line,group = 1)) +
  geom_col(aes(y=Bar*sfactor))+
  scale_y_continuous("Line",
                     sec.axis = sec_axis(trans= ~. /sfactor, name = "Bar"))

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! One more request: how to label the bars? Adding > geom_text(aes(label=Bar)) doesn't seem to work. Thanks a lot
@wellokaythen I would suggest you to add the labels after each geom so like this: geom_col(aes(y=Bar*sfactor))+geom_text(aes(y=Bar*sfactor,label=Bar)) !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.