2

This is the code and dataframe I used for my analysis for creating bar & line chart.

I am trying to create a graph where it shows visit_frequency (bar chart) on Primary Y axis and visit_duration_avg (line chart) on Secondary Y axis and it should show visit_sequence_number on X axis

library(ggplot2)

df<- data.frame(visit_sequence_number=c(1:5),
                visit_frequency=c(697754,416613,263433,178823,128599),
                visit_duration_avg=c(133,121,121,122,124))


ggplot(df)  + 
  geom_bar(aes(x=visit_sequence_number, y=visit_frequency),stat="identity",fill="tan1", colour="sienna3")+
  geom_line(aes(x=visit_sequence_number, y=visit_duration_avg*max(df$visit_frequency)),stat="identity")+
  geom_text(aes(label=visit_duration_avg, x=visit_sequence_number,
                y=visit_duration_avg*max(df$visit_frequency)), colour="black")+
  geom_text(aes(label=visit_frequency, x=visit_sequence_number, y=0.95*visit_frequency), colour="black")+
  scale_y_continuous(sec.axis = sec_axis(~./max(df$visit_frequency)))
zx8754
  • 52,746
  • 12
  • 114
  • 209
Yogesh Kumar
  • 609
  • 6
  • 22
  • What is your question? – LAP May 09 '18 at 07:39
  • I am trying to create a graph where it shows visit_frequency (bar chart) on Primary Y axis and visit_duration_avg (line chart) on Secondary Y axis and it should show visit_sequence_number on X axis . – Yogesh Kumar May 09 '18 at 07:42
  • Why do you multiply your duration averages by the maximum visit frequency, and not by the corresponding visit frequency per row? – LAP May 09 '18 at 07:58
  • @LAP :How do I do that ? multiplying corresponding visit frequency per row ? – Yogesh Kumar May 09 '18 at 08:04
  • Just use `visit_duration_avg*visit_frequency` instead of `visit_duration_avg*max(df$visit_frequency)` – LAP May 09 '18 at 08:08
  • It does not work , and i get error like Error in geom_text(aes(label = visit_frequnecy, x = visit_sequence_number, : non-numeric argument to binary operator – Yogesh Kumar May 09 '18 at 08:17
  • It works for me, maybe it's a typo? `(label = visit_frequnecy,` in your error above. – LAP May 09 '18 at 08:40
  • It did not work for me .....it is not a typo....I simply used code from the below solution and this did not work for me .... https://stackoverflow.com/questions/41764312/combining-bar-and-line-chart-double-axis-in-ggplot2 – Yogesh Kumar May 09 '18 at 09:02

1 Answers1

0

This is not possible with ggplot2. Please see the following answer from the creator of the package (Hadley Wickham):

https://stackoverflow.com/a/3101876/8357864

LetEpsilonBeLessThanZero
  • 2,395
  • 2
  • 12
  • 22