首页 > 解决方案 > 如何使用 ggplot (R studio) 绘制其中项目由分类列分隔的绘图?

问题描述

从类似于以下的矩阵(但要大一点),在我的环境中保存为“vb”:

Food    Counts  se  Category
Apple   3   1   Fruit
Cauliflower 4   0.5 Vegetable
Banana  1   3   Fruit
Pear    7   3.2 Fruit
Broccoli    4   1.4 Vegetable
Brussel's sprouts   7   7   Vegetable

我想制作一个图表,显示不同食物的计数+标准误差,按“类别”组织(即,水果和蔬菜聚集在不同的地块中)。我习惯于在 R 中使用以下代码:

ggplot(vb, aes(y=Counts, x=Food)) + 
  geom_point(color="#104E8B") +
  geom_errorbar(aes(ymin=Counts-2*se, ymax=Counts+2*se), width=.2,color="#104E8B") +
  facet_grid(Category ~ ., scales = "free", space = "free_y") +
  ylim(0, 10) +
  coord_flip() 

但是,这仍然会在蔬菜旁边列出水果,反之亦然。它只省略了属于其他类别的食物的数据点, 参见图片以供参考。

如何让“水果”情节只列出水果,让“蔬菜”情节只列出蔬菜?

dput 格式的数据。

vb <-
structure(list(Food = c("Apple", "Cauliflower", "Banana", 
"Pear", "Broccoli", "Brussel's sprouts"), Counts = c(3L, 
4L, 1L, 7L, 4L, 7L), se = c(1, 0.5, 3, 3.2, 1.4, 7), 
Category = structure(c(1L, 2L, 1L, 1L, 2L, 2L), 
.Label = c("Fruit", "Vegetable"), class = "factor")), 
row.names = c(NA, -6L), class = "data.frame")

标签: rggplot2facet-grid

解决方案


推荐阅读