R - Barplot,其中变量的一个子集是填充,一个子集是y轴?

时间:2018-05-02 14:03:43

标签: r ggplot2 dplyr

我想在x轴上绘制xExp和yExp,将Yes / Nos作为堆叠填充,将xDur,yDur作为y轴。这可能吗? Exp =经验,Dur =持续时间。

这是我最近尝试的内容:

ggplot(md1,aes(variable,value,fill=str_detect("Exp")))+
geom_bar(stat="identity")

我融化了数据框并对其进行了过滤,现在看起来如下所示。我有比这更多的Exp和Dur值,将它们保存为单独的列是否有意义?

md1 <- md %>% 
filter(str_detect(variable, paste(c("Exp","Dur"),collapse = '|')))

Subject variable    value
1   xExp    Yes
2   xExp    No
3   xExp    Yes
4   xExp    Yes
5   xExp    No
1   xDur    2
2   xDur    NA
3   xDur    1
4   xDur    10
5   xDur    NA
1   yExp    No
2   yExp    No
3   yExp    Yes
4   yExp    Yes
5   yExp    No
1   yDur    NA
2   yDur    5
3   yDur    8
4   yDur    2
5   yDur    NA

感谢您的帮助!我一直在这里搜索,无法找到我需要的东西,但也许我正在寻找错误的东西。

1 个答案:

答案 0 :(得分:1)

[DllImport("..\\..\\dll\\StclDevices.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int SendFrame(UInt32 deviceIndex, LaserPoint[] pData, UInt32 numOfPoints, UInt32 scanrate);

我想知道这是不是你的目标

txt <- tibble::tribble(
  ~Subject,~variable,~value,
           1,   "xExp"   , "Yes",
            2,   "xExp"  ,  "No",
           3 ,  "xExp"   , "Yes",
           4 ,  "xExp"   , "Yes",
            5  , "xExp"  ,  "No",
             1,   "xDur" ,   "2",
            2 ,  "xDur"  ,  "NA",
             3,   "xDur" ,   "1",
            4 ,  "xDur"  ,  "10",
            5 ,  "xDur"  ,  "NA",
            1 ,  "yExp"  ,  "No",
            2 ,  "yExp"  ,  "No",
           3  , "yExp"   , "Yes",
           4  , "yExp"  ,  "Yes",
            5 ,  "yExp"  ,  "No",
            1 ,  "yDur"  ,  "NA",
             2 ,  "yDur"  ,  "5",
             3 ,  "yDur" ,   "8",
             4 ,  "yDur"  ,  "2",
            5  , "yDur"   , "NA"
  )

所以图表看起来像这样

library(tidyr)
library(dplyr)
library(ggplot2)    

df <- txt %>% 
  mutate(variable=gsub("([[:lower:]])([[:upper:]][[:lower:]])", "\\1 \\2", variable)) %>% 
  separate(variable, into=c("xy", "what")) %>% 
  spread(what, value) %>% 
  readr::type_convert() 

df
#> # A tibble: 10 x 4
#>    Subject xy      Dur Exp  
#>  *   <dbl> <chr> <int> <chr>
#>  1       1 x         2 Yes  
#>  2       1 y        NA No   
#>  3       2 x        NA No   
#>  4       2 y         5 No   
#>  5       3 x         1 Yes  
#>  6       3 y         8 Yes  
#>  7       4 x        10 Yes  
#>  8       4 y         2 Yes  
#>  9       5 x        NA No   
#> 10       5 y        NA No   

enter image description here