每次我制作一个固定的条形图时,如果有一个没有数据的部分,那么出于对称的目的,这个图仍然会为它制造一个点,因此看起来这些变量都经过了测试,得到的值是0,但事实并非如此.有没有办法覆盖ggploy.下面是一个示例,其中第8节A3看起来像是记录了0值,但实际上并未在数据集中进行调查.

library(ggplot2)
library(dplyr)

# Your data
data <- data.frame(A = c(1, 2, 3, 1, 2, 3, 1, 2, 1, 2), 
                   B = c(5, 34, 5, 34, 34, 56, 3, 3, 6, 35), 
                   C = c("Light","Light", "Light", "Dark", "Dark", "Dark", "Light","Light", "Dark", "Dark"), 
                   D = c(4, 4, 4, 4, 4, 4, 8, 8, 8, 8))


# Create plots
Plot1 <- ggplot(data, aes(x = A, y = B, fill = C)) +
  geom_bar(stat = "identity", position = position_dodge2(preserve = "single"))  +
  theme_minimal() + theme(legend.position = "right") +
  facet_wrap(~D)

Plot1

enter image description here

推荐答案

Scales="Free_x"删除未使用的x值

如果希望保持所有条的大小相同,请使用带有space参数的facet_grid.

下面在ggplot2中提供的解决方案--也是ggblket

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

# Your data
data <- data.frame(A = c(1, 2, 3, 1, 2, 3, 1, 2, 1, 2), 
                   B = c(5, 34, 5, 34, 34, 56, 3, 3, 6, 35), 
                   C = c("Light","Light", "Light", "Dark", "Dark", "Dark", "Light","Light", "Dark", "Dark"), 
                   D = c(4, 4, 4, 4, 4, 4, 8, 8, 8, 8))


# Create plots
Plot1 <- ggplot(data, aes(x = A, y = B, fill = C)) +
  geom_bar(stat = "identity", position = position_dodge2(preserve = "single"))  +
  theme_minimal() + 
  theme(legend.position = "right") +
  facet_grid(.~D, scales = "free_x", space = "free_x") +
  scale_x_continuous(breaks = 1:3)

Plot1


library(ggblanket)

data |> 
  gg_col(
    x = A, 
    y = B, 
    col = C,
    facet = D,
    position = position_dodge2(preserve = "single"),
    facet_layout = "grid",
    facet_scales = "free_x",
    facet_space = "free_x",
    x_breaks = 1:3,
  )
#> Warning in gg_blanket(data = data, geom = "col", stat = stat, position = position, : Ignoring unknown parameters: `contour`
#> Ignoring unknown parameters: `contour`

创建于2024-02-24,共reprex v2.1.0

R相关问答推荐

提取rame中对应r中某个变量的n个最小正值和n个最大负值的条目

x[[1]]中的错误:脚注越界

如何使用R中的dhrr函数将李克特量表的因子列从长转换为宽?

基于不同组的列的相关性

修改用R编写的用户定义函数

将嵌套列表子集化为嵌套列表

par函数中的缩写,比如mgp,mar,mai是如何被破译的?

如果某些列全部为NA,则更改列

为了网络分析目的,将数据框转换为长格式列联表

找出二叉树中每个 node 在R中的深度?

如何读取CSV的特定列时,给定标题作为向量

如何用书面利率绘制geom_bar图

R中的类别比较

有没有办法一次粘贴所有列

是否可以将线性模型的p值添加到tbl_summary中

在同一单元格中创建包含整数和百分比的交叉表

R:如何在数据集中使用Apply

对一个数据帧中另一个数据帧中的值进行计数

在子图内和子图之间对齐行数不均匀的表格罗布对

如果缺少时间,如何向日期-时间列添加时间