R中的条形图分组,每组四个条形

时间:2018-09-28 20:02:08

标签: r ggplot2 geom-bar

所以基本上我想弄清楚如何使ggplot2中的条形图看起来像这样-并失败了...

enter image description here

这是我的数据

DF <- structure(list(Location = c("PC_of_recapped_cells", "PC_of_infested_cells", 
"PC_Recapped_and_Infested", "PC_Normal_mites"), S1 = c(7.31, 
3.2, 85.71, 85.71), S2 = c(7.46, 2.63, 83.33, 100), S3 = c(12.17, 
11.3, 30.77, 69.23), S4 = c(10.77, 5.72, 82.35, 76.47), C1 = c(6.59, 
0, 0, 0), C2 = c(15.94, 0, 0, 0), TS3 = c(14.97, 16.77, 25, 39.29
)), .Names = c("Location", "S1", "S2", "S3", "S4", "C1", "C2", 
"TS3"), class = "data.frame", row.names = c(NA, -4L))

“错误:col_names必须为TRUE,FALSE或字符向量”

1 个答案:

答案 0 :(得分:1)

首先通过将空格更改为逗号来对文本文件进行一些手动清理:

Location,S1,S2,S3,S4,C1,C2,TS3
PC_of_recapped_cells,7.31,7.46,12.17,10.77,6.59,15.94,14.97
PC_of_infested_cells,3.20,2.63,11.30,5.72,0.00,0.00,16.77
PC_Recapped_and_Infested,85.71,83.33,30.77,82.35,0.00,0.00,25.00
PC_Normal_mites,85.71,100.00,69.23,76.47,0.00,0.00,39.29

然后,您可以使用tidyverse read_csv()函数加载数据并按如下所示调整其形状:

library(tidyverse)
df <-
  file_path %>% 
  read_csv() %>% 
  gather(key = type, value = pct, -Location) %>% 
  mutate(type = fct_relevel(type, c("S1", "S2", "S3", "S4", "C1", "C2", "TS3")))

df
   Location                 type     pct
   <chr>                    <chr>  <dbl>
 1 PC_of_recapped_cells     S1      7.31
 2 PC_of_infested_cells     S1      3.2 
 3 PC_Recapped_and_Infested S1     85.7 
 4 PC_Normal_mites          S1     85.7 
 5 PC_of_recapped_cells     S2      7.46
 6 PC_of_infested_cells     S2      2.63
...

然后可以绘制它:

df %>% 
  ggplot(aes(x = type, y = pct, fill = Location)) + 
  geom_col(position = "dodge") +
  theme(legend.position = "bottom")

在重新着色,重命名标签和进行其他更改时,您应该可以从那里获得它。