Search code examples
rplotlyr-plotlyggplotly

R 1 column with bar chart the other 3 as lines on the same chart


I have a dataframe with a date for the x axis and would like to plot the count as a barchart(vertical) and the mean,lower_conf, and upper_conf as horizontal lines. The following is my dataframe.

   Date        Count  Mean      X95_lower_conf  X95_upper_conf
0  2018-11-01  1      5.225806  1.494764        8.956849
1  2018-11-02  0      5.225806  1.494764        8.956849
2  2018-11-03  21     5.225806  1.494764        8.956849
3  2018-11-04  1      5.225806  1.494764        8.956849
4  2018-11-05  0      5.225806  1.494764        8.956849
5  2018-11-06  0      5.225806  1.494764        8.956849

I have tried many different ways to accomplish this but I am having issues, this is one that I have tried:

plot_ly(df1, x = ~Date, y = ~Mean, name = 'Mean') %>%
  add_trace(y = ~X95_upper_conf, name = 'Upper Confidence', type = 'scatter', mode = 'lines') %>%
  add_trace(y = ~X95_lower_conf, name = 'Lower Confidence', type = 'scatter', mode = 'lines') %>%
  add_trace(y = ~Count, name = 'Count', type = 'bar',mode = 'lines')

Any help on tweaking this to get my desired output would be greatly appreciated!


Solution

  • Using ggplot2:

    library(ggplot2)
    
    ggplot(df1) +
      geom_col(aes(Date, Count)) +
      geom_hline(aes(yintercept = Mean)) +
      geom_hline(aes(yintercept = X95_lower_conf)) +
      geom_hline(aes(yintercept = X95_upper_conf))