代码之家  ›  专栏  ›  技术社区  ›  Nono_sad

R:GGPLOT2在一个绘图中绘制多个数据帧

  •  0
  • Nono_sad  · 技术社区  · 6 年前

    我有点困在ggplot2试图在一个图中绘制几个数据帧。

    这里有几个数据框,我只举两个例子。

    数据帧具有相同的头,但不同。假设我想数两个盒子里的球。

    name=c('red','blue','green','purple','white','black')
    value1=c(2,3,4,2,6,8)
    value2=c(1,5,7,3,4,2)
    
    test1=data.frame("Color"=name,"Count"=value1)
    test2=data.frame("Color"=name,"Count"=value2)
    

    我想做的是把我的伯爵画成条形图。 目前我所做的是:

    (plot_test=ggplot(NULL, aes(x= Color, y=Count)) + 
        geom_bar(data=test1,stat = "identity",color='green')+
        geom_bar(data=test2,stat = "identity",color='blue')
    )
    

    Problem is that my plots are overlapping themselves

    我想要x=color和y=count,并在test1旁边绘制test2数据帧的条形图。这里有重叠的部分。所以我在x中会有两个相同的名字,但是我想用几种颜色绘制数据帧,并在图例中得到这个名字。

    例如“绿色条”=test1 “蓝条”=测试2

    谢谢你的时间和帮助。

    最好的问候

    3 回复  |  直到 6 年前
        1
  •  3
  •   karen    6 年前

    试试这个:

    name=c('red','blue','green','purple','white','black')
    value1=c(2,3,4,2,6,8)
    value2=c(1,5,7,3,4,2)
    
    test1=data.frame("Color"=name,"Count"=value1)
    test2=data.frame("Color"=name,"Count"=value2)
    
    test1$var <- 'test1'
    test2$var <- 'test2'
    
    test_all <- rbind(test1,test2)
    
    
    (plot_test=ggplot(data=test_all) + 
      geom_bar(aes(x=Color,y=Count,color=var),
               stat = "identity", position=position_dodge(1))+
      scale_color_manual(values = c('green', 'blue'))
    )
    
        2
  •  2
  •   DS_UNI    6 年前

    你有两个选择:

    调整条的大小和位置

    ggplot(NULL, aes(x= Color, y=Count)) + 
    geom_bar(data=test1, aes(color='test1'), stat = "identity",
             width=.4, position=position_nudge(x = -0.2)) +
    geom_bar(data=test2, aes(color='test2'), stat = "identity", 
             width=.4, position=position_nudge(x = 0.2))
    

    enter image description here 或者我建议将两个数据帧连接在一起,然后绘制

    library(dplyr)
    test1 %>% 
      full_join(test2, by = 'Color') %>% 
      data.table::melt(id.vars = 'Color') %>% 
      ggplot(aes(x= Color, y=value, fill = variable)) + 
      geom_bar(stat = "identity", position = 'dodge')
    

    enter image description here

        3
  •  0
  •   Michael Henry    6 年前

    这将执行您试图执行的操作:

    balls <- data.frame(
      count = c(c(2,3,4,2,6,8),c(1,5,7,3,4,2)),
      colour = c(c('red','blue','green','purple','white','black'),c('red','blue','green','purple','white','black')),
      box = c(rep("1", times = 6), rep("2", times = 6))
    )
    
    ggplot(balls, aes(x = colour, y = count, fill = box)) +
      geom_col() +
      scale_fill_manual(values = c("green","blue"))
    

    这更好,因为它有助于比较框计数:

    ggplot(balls, aes(x = colour, y = count)) +
      geom_col() +
      facet_wrap(~ box, ncol = 1, labeller = as_labeller(c("1" = "Box #1", "2" = "Box #2")))