How can a line be overlaid on a bar plot using ggplot2?

后端 未结 2 1296
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 20:14

I\'m looking for a way to plot a bar chart containing two different series, hide the bars for one of the series and instead have a line (smooth if possible) go through the t

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-28 20:33

    You can get group totals in many ways. One of them is

    with(df, tapply(val, grp, sum))
    

    For simplicity, you can combine bar and line data into a single dataset.

    df_all <- data.frame(grp = factor(levels(df$grp)))
    df_all$bar_heights <- with(df, tapply(val, grp, sum))
    df_all$line_y <- with(df2, tapply(val, grp, sum))
    

    Bar charts use a categorical x-axis. To overlay a line you will need to convert the axis to be numeric.

    ggplot(df_all) +
       geom_bar(aes(x = grp, weight = bar_heights)) +
       geom_line(aes(x = as.numeric(grp), y = line_y))
    

    enter image description here

提交回复
热议问题