在ggplot2中用直方图覆盖boxplot

时间:2018-03-25 03:55:02

标签: r ggplot2

您好我想用R脚本创建一个类似的图表,如下所示:

enter image description here

取自:https://community.tableau.com/thread/194440

这是我在R中的代码:

<%= @ssl_cert %>

然而我得到以下错误:

library(ggplot2)

ifile <- read.table("C:/ifiles/test.txt", skip = 2, header = TRUE, sep="\t")
ifileVI <- data.frame(ifile["VI"], ifile["Site"])
x<-quantile(ifileVI$VI,c(0.01,0.99))
data_clean <- ifileVI[bfileVI$VI >=x[1] & ifileVI$VI <=x[2],]

p <- ggplot(data_clean, aes(x = Site, y = VI, group=Site)) + geom_boxplot() + geom_histogram(binwidth = 0.05)

p

bfileVI:

&#13;
&#13;
Error: stat_bin() must not be used with a y aesthetic.
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:5)

您可以尝试用矩形替换直方图以生成如下图:

enter image description here

如何做到这一点:

生成随机数据

df <- data.frame(State = LETTERS[1:3],
                 Y = sample(1:10, 30, replace = TRUE),
                 X = rep(1:10, 3))

用矩形替换直方图

library(ggplot2)

# You can plot geom_histogram or bar (pre-counted stats)
ggplot(df, aes(X, Y)) +
    geom_bar(stat = "identity", position = "dodge") +
    facet_grid(State ~ .)
# Or you can plot similar figure with geom_rect
ggplot(df)  +
    geom_rect(aes(xmin = X - 0.4, xmax = X + 0.4, ymin = 0, ymax = Y)) +
    facet_grid(State ~ .)

添加boxplot

要添加boxplot,我们需要:

  1. 翻转坐标(函数coord_flip
  2. geom_rect
  3. 中切换X和Y值

    代码:

    ggplot(df)  +
        geom_rect(aes(xmin = 0, xmax = Y, ymin = X - 0.4, ymax = X + 0.4)) +
        geom_boxplot(aes(X, Y)) +
        coord_flip() +
        facet_grid(State ~ .)
    

    结果:

    enter image description here

    具有更好视觉效果的最终情节代码

    ggplot(df)  +
        geom_rect(aes(xmin = 0, xmax = Y, ymin = X - 0.4, ymax = X + 0.4),
                  fill = "blue", color = "black") +
        geom_boxplot(aes(X, Y), alpha = 0.7, fill = "salmon2") +
        coord_flip() +
        facet_grid(State ~ .) +
        theme_classic() +
        scale_y_continuous(breaks = 1:max(df$X))
    

答案 1 :(得分:1)

您收到Error: stat_bin() must not be used with a y aesthetic.,因为您无法在直方图的美学中指定y。如果要混合具有不同参数的图,则需要提供独特的美学效果。我会用iris来证明:

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram(binwidth = 0.05) +
  geom_boxplot(aes(x = 3, y = Sepal.Width))

不幸的是,boxplots的默认值是垂直的,因为直方图是水平的,coord_flip()是全有或全无,所以你留下了这个可怕的东西:enter image description here

我能想出的最好不是让它们重叠,而是用gridExtra包把它们放在另一个上面:

a <- ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram(binwidth = 0.05) 

b <- ggplot(iris, aes(x = "", y = Sepal.Width)) + 
  geom_boxplot() + 
  coord_flip()

grid.arrange(a,b,nrow=2)

给了我们一些非常好的东西:enter image description here

答案 2 :(得分:1)

一个很好的例子,其中ggstance包很方便。

library(ggplot2)
library(ggstance)

ggplot(iris, aes(x = Sepal.Length)) +
  geom_histogram() +
  geom_boxploth(aes(y = 3), width = 2, color = "blue", lwd = 2, alpha = .5) +
  theme_minimal() +
  facet_wrap(~Species, ncol = 1)

enter image description here

相关问题