简体   繁体   中英

How to overlay a bar plot on the line with difference of two lines in ggplot?

Here is a plot from ggplot by some codes like this:

p <- ggplot(db,aes(x,value,color=variable))
p <- p+geom_line(size=1)
p <- p+geom_point()
p+facet_wrap(facets = ~gp, scale = 'free_x')

在此处输入图片说明

I want to add a bar plot to the figure to show the difference of two lines, since the difference is not that easy to compare in the plot. What should I do now? Add a new level in the variable and calculate the difference by hand (which can add another line instead of bars in the graph)?

The dataset is here:

> db
   gp  x variable   value
1  13  1    mode1 71.3756
2  13  4    mode1 74.1380
3  13  7    mode1 74.5840
4  13 10    mode1 74.7552
5  13 13    mode1 74.8452
6  13 16    mode1 74.9004
7  13 19    mode1 74.9380
8  16  1    mode1 71.4320
9  16  4    mode1 74.2012
10 16  7    mode1 74.6484
11 16 10    mode1 74.8204
12 16 13    mode1 74.9104
13 16 16    mode1 74.9660
14 16 19    mode1 75.0036
15 19  1    mode1 71.4708
16 19  4    mode1 74.2448
17 19  7    mode1 74.6928
18 19 10    mode1 74.8652
19 19 13    mode1 74.9556
20 19 16    mode1 75.0112
21 19 19    mode1 75.0488
22 13  1    mode2 77.2172
23 13  4    mode2 78.8460
24 13  7    mode2 79.4080
25 13 10    mode2 79.6844
26 13 13    mode2 79.8472
27 13 16    mode2 79.9544
28 13 19    mode2 80.0320
29 16  1    mode2 77.2884
30 16  4    mode2 78.9224
31 16  7    mode2 79.4864
32 16 10    mode2 79.7636
33 16 13    mode2 79.9268
34 16 16    mode2 80.0360
35 16 19    mode2 80.1120
36 19  1    mode2 77.3376
37 19  4    mode2 78.9752
38 19  7    mode2 79.5404
39 19 10    mode2 79.8180
40 19 13    mode2 79.9820
41 19 16    mode2 80.0880
42 19 19    mode2 80.1640

You can use the stat_summary function to calculate the difference using the diff function. Furthermore, you have to remove the color aesthetics from the ggplot and add it to both geom_line and geom_point .

library(ggplot2)
ggplot(db, aes(x, value)) +
  geom_line(size = 1, aes(color = variable)) +
  geom_point(aes(color = variable)) +
  facet_wrap(facets = ~ gp, scale = 'free_x') +
  stat_summary(fun.y = diff, geom = "bar")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM