在同一个图中表示geom_line和geom_bar [英] Represent geom_line and geom_bar in the same plot

查看:314
本文介绍了在同一个图中表示geom_line和geom_bar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数据:

  DF = structure(list(Exp = 1:12,cat_o = c(0.5,5 ,1.5,1,2,6,10.3333333333333,
9.33333333333333,13,6,6,0),cat_y = c(2,0,4,5,27,17.5,
9.33333333333333,6.5, cat_3 = c(34,40.5,28.5,
36.5,20,19.3333333333333,23.5,15.8333333333333,25.27.3333333333333,
8.16666666666667,16),cat_density = c( 37L,65L,83L,82L,97L,
36L,33L,52L,31L,33L,19L,28L)),.Names = c(Exp,cat_o,
cat_y ,cat3,cat_density),class =data.frame,row.names = c(NA,
-12L))

我想表示 cat_o cat_y geom_line 和 cat_density ,通过使用 geom_bar / code>。输出应该是 cat_density cat_o cat_y cat3 在同一个图中。



编辑:
我发现的所有东西都是可能的两个不同的地块覆盖(组织和曲线),但对于同一列。


Here's my datas:

DF=structure(list(Exp = 1:12, cat_o = c(0.5, 5, 1.5, 1, 2, 6, 10.3333333333333, 
9.33333333333333, 13, 6, 6, 0), cat_y = c(2, 0, 4, 5, 27, 17.5, 
9.33333333333333, 6.5, 5, 8, 0, 0), cat3 = c(34, 40.5, 28.5, 
36.5, 20, 19.3333333333333, 23.5, 15.8333333333333, 25, 27.3333333333333, 
8.16666666666667, 16), cat_density = c(37L, 65L, 83L, 82L, 97L, 
36L, 33L, 52L, 31L, 33L, 19L, 28L)), .Names = c("Exp", "cat_o", 
"cat_y", "cat3", "cat_density"), class = "data.frame", row.names = c(NA, 
-12L))

I want to represent cat_o cat_y cat3 by using geom_line and cat_density by using geom_bar. The output should be an histogram for cat_density and lines for cat_o cat_y cat3 in the same plot.

EDIT: All what I have found is it is possible two differents plots overlayed (histo and curve) but for the same column. Here.

How to do this in the same ggplot ?

Thanks a lot.

解决方案

First, you may find it helpful to tidy the data.frame. Then, you can do this by filtering the data.frame -- it will be important to plot the geom_bar "behind" the geom_line:

library(tidyverse)

df.tidy <- gather(DF, metric, value, -Exp)

ggplot(data = df.tidy, aes(x = Exp, y = value)) +
  geom_bar(data = filter(df.tidy, metric == "cat_density"), stat = "identity") +
  geom_line(data = filter(df.tidy, metric != "cat_density"), aes(col = metric, group = metric))

这篇关于在同一个图中表示geom_line和geom_bar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆