在ggplot2中使用直方图覆盖boxplot [英] Overlaying boxplot with histogram in ggplot2

查看:102
本文介绍了在ggplot2中使用直方图覆盖boxplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用R脚本创建一个如下图所示的图表:

Hi I want to create a similar chart as shown below with R script:

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

这是我在R中的代码:

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

但是我收到以下错误:

Error: stat_bin() must not be used with a y aesthetic.

bfileVI:

Id	    VI	Site
WFR1	2.91	1
WFR1	2.89	2
WFR1	2.86	3
WFR1	2.91	4
WFR1	2.87	1
WFR1	2.67	2
WFR1	2.76	3
WFR1	2.74	4
WFR1	2.98	4
WFR1	2.89	3
WFR1	2.55	4
WFR1	2.96	3
WFR1	2.71	1
WFR1	2.98	2
WFR1	2.89	3
WFR2	2.55	2
WFR2	2.86	4
WFR2	2.91	3
WFR2	287	1
WFR2	2.74	2
WFR2	2.98	1
WFR2	2.89	2
WFR2	2.55	3
WFR2	2.96	4
WFR2	2.71	1
WFR2	2.86	2
WFR2	2.91	3
WFR2	287	4
WFR2	2.67	1
WFR2	2.76	2
WFR2	2.74	3
WFR2	2.98	4
WFR2	2.89	1
WFR2	2.55	2
WFR2	2.96	3
WFR2	2.71	4
WFR2	2.98	1
WFR2	2.89	2
WFR2	2.55	3
WFR2	2.86	4

推荐答案

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

You can try to replace histogram with rectangles to generate a plot like this:

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 ~ .)

添加箱线图

要添加箱线图,我们需要:

Add boxplot

To add boxplot we need to:

  1. 翻转坐标(功能coord_flip)
  2. geom_rect
  3. 中切换X和Y值
  1. Flip coordinates (function coord_flip)
  2. Switch X and Y values in geom_rect

代码:

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 ~ .)

结果:

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))

这篇关于在ggplot2中使用直方图覆盖boxplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆