首页 > 解决方案 > 具有不连续 x 轴的直方图

问题描述

我需要在 R 中实现直方图。我添加了一张图片来表示所需的结果。我曾尝试同时使用ggplot2和基本功能hist。我使用此代码(ggplot)来获取基本直方图,但我想添加选项以设置 x 轴,如图所示(完全相同的值)。有人可以告诉我该怎么做吗?

我的输入文件DataLig2包含一个对象列表,每个对象都关联一个值(N..of.similar..Glob.Sum...0.83..ligandable.pockets)。我需要绘制所有报告值的频率。最小值是 1,最大值是 28。没有从 16 到 27 的值,所以我想在我的图中跳过这个范围。

输入文件示例:

Object;N..of.similar..Glob.Sum...0.83..ligandable.pockets
1b47_A_001;3
4re2_B_003;1
657w_H_004_13
1gtr_A_003;28
...

我的脚本:

ggplot(dataLig2, aes(dataLig2$N..of.similar..Glob.Sum...0.83..ligandable.pockets, fill = group)) + geom_histogram(color="black") + 
  scale_fill_manual(values = c("1-5" = "olivedrab1",
                               "6-10" = "limegreen",
                               "11-28" = "green4"))

您是否还可以建议一个带有hist基本函数的脚本来获得相同的图表(如图所示带有间隔条)?谢谢!

在此处输入图像描述

标签: r

解决方案


使用ggplot,将 x 设置为因子,将缺少的数字设置为“...”,并设置为绘制未使用的级别,请参见示例:

library(ggplot2)

# reproducible example data
# where 8 and 9 is missing
set.seed(1); d <- data.frame(x = sample(c(1:7, 10), 100, replace = TRUE))

# add missing 8 and 9 as labels
d$x1 <- factor(d$x, levels = 1:10, labels = c(1:7, "...", "...", 10))

#compare
cowplot::plot_grid(
  ggplot(d, aes(x)) +
    geom_bar() +
    ggtitle("before") +
    scale_x_continuous(breaks = 1:10),
  ggplot(d, aes(x = x1)) +
    geom_bar() +
    scale_x_discrete(drop = FALSE) +
    ggtitle("after"))

在此处输入图像描述


推荐阅读