r - 忽略分面图中没有数据的 x 轴级别并更改条形的宽度

标签 r ggplot2

正如您在下面的数据中看到的,某些分面变量“items”缺少 x 轴变量“type”的某些级别。例如,“items = 32”没有“type = A”。

我想消除沿 x 轴对应于不存在的“类型”的空白(例如,对于 32 个项目的情况,类型 A)。

一些数据(“临时”):

 type   items     value
    A      16       6.3
    B      16       8.3
    C      16       7.9
    B      32       7.7
    C      32       8.3
    C      64       7.9

绘图代码:

library(ggplot2)
ggplot(temp, aes(x = type, y = value, fill = type)) + 
  geom_bar(stat = "identity") + 
  facet_grid( . ~ items)

enter image description here

========================

编辑:

根据 Joran 的解决方案,设置 scales = "free_x" 就是我想要的。然而,在项目编号 32 和 64 下,条形的宽度变得非常大。请帮助我使所有条形的宽度均匀。

ggplot(temp, aes(x = type, y = value, fill = type)) + 
  geom_bar(stat = "identity") + 
  facet_grid( . ~ items, scales = "free_x")

enter image description here

最佳答案

只需遵循 joran 给出的指示即可和 Etienne Low-Décarie结束这个未解答的问题。请投票joranEtienne Low-Décarie .

另外,请注意Roman Luštrik上面的宝贵评论“我希望您有充分的理由这样做。空白区域的信息非常丰富,它让读者知道这些级别的值为 0(这仍然是一个值)。”

# data
temp <- structure(list(type = structure(c(1L, 2L, 3L, 2L, 3L, 3L), .Label = c("A", 
"B", "C"), class = "factor"), items = c(16L, 16L, 16L, 32L, 32L, 
64L), value = c(6.3, 8.3, 7.9, 7.7, 8.3, 7.9)), .Names = c("type", 
"items", "value"), class = "data.frame", row.names = c(NA, -6L
))

# plot
library(ggplot2)
ggplot(temp, aes(type, value, fill = type)) + 
  geom_bar(stat = "identity") + 
  facet_grid( . ~ items, scales = "free_x", space = "free") 

enter image description here

关于r - 忽略分面图中没有数据的 x 轴级别并更改条形的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11278255/

相关文章:

r - 将 LaTex 中的\to 符号放入 R 中的 ggplot2

从 ggplot 中删除 n 个图例

r tidyverse - 计算具有相同名称的多个列的平均值

r - 在 S3 函数重载中应该把省略号放在哪里?

r - 如何阻止 renderTable 默认为小数点后两位?

r - 如何将ggplot标题与窗口而不是绘图网格对齐?

r - 如何在 R 版本 3.2.1 for Mac 中安装 ggplot2

r - 如何在 R 中将绘图保存为黑白(无灰色像素)图像?

r - 如何循环遍历 R 中的 CSV 文件文件夹

r - 如何预先确定互斥比较?