您好我想用R脚本创建一个类似的图表,如下所示:
取自: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:
Error: stat_bin() must not be used with a y aesthetic.
&#13;
答案 0 :(得分:5)
您可以尝试用矩形替换直方图以生成如下图:
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,我们需要:
coord_flip
)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))
答案 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()
是全有或全无,所以你留下了这个可怕的东西:
我能想出的最好不是让它们重叠,而是用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)
答案 2 :(得分:1)