繁体   English   中英

在ggplot中的躲避条之间添加空格

[英]Adding a space between dodged bars in ggplot

有谁知道如何在条形图中的一些闪避的条之间添加一个空格(将蓝色与橙色条分开)? 具体来说,我想在下面显示的代码中在红色和蓝色条之间添加一个小间隙!

library(ggplot2)
library(scales)
library(reshape)

dat <- read.table(text = "    ONE TWO THREE
                  1   23  234 324
                  2   34  534 12
                  3   56  324 124
                  4   34  234 124
                  5   123 534 654",sep = "",header = TRUE)

str(dat)
datm <- melt(cbind(dat, ind = rownames(dat)), id.vars = c('ind'))
str(datm)
colnames(datm)
rownames(datm)


ggplot(datm,aes(x = variable, y = value,fill = ind)) + 
  geom_bar(position = "fill",stat = "identity") +
  coord_flip()

ggplot(datm, aes(x = variable, y = ifelse(ind %in% 1:2, -value, value), fill = ind)) + 
    geom_col() +
    coord_flip()

df <- data.frame(
  supp = rep(c("VC", "OJ"), each = 3),
  dose = rep(c("D0.5", "D1", "D2"), 2),
  len = c(6.8, 15, 33, -4.2, -10, -29.5)
  )
str(df)
head(df)
p <- ggplot(df, aes(x = dose, y = len))+
  geom_col(aes(fill = supp), width = 0.7)
p

df3 <- read.table(
text = 
"region group metric somevalue
blue T1 epsilon 63
blue T2 epsilon -40
red T1 epsilon 100
blue T1 kappa 19
blue T2 kappa -30
red T1 kappa 75
blue T1 zulu  50
blue T2 zulu -18
red T1 zulu 68", header=TRUE)

library(ggpubr)

tabledf <- data.frame(a = 1:6, b = rnorm(6))
colnames(tabledf) <- c("P&L", "Exp. Change*")
rownames (tabledf) <- NULL

stable.p <- ggtexttable(tabledf, rows = NULL, theme = ttheme("default", base_size = 11))

library(dplyr)
library(tidyr)
library(ggpmisc)
library(gridExtra)

df3$region <- factor(df3$region, levels = c("red", "blue"))
df3_neg <- filter(df3, somevalue < 0) %>% 
  tidyr::complete(region, group, metric)

df3_pos<- filter(df3, somevalue > 0) %>% 
  tidyr::complete(region, group, metric)

p2 <- ggplot(df3, aes(somevalue, metric)) +
  geom_col(aes(alpha = group, fill=region), data = df3_pos, position = "dodge", na.rm = TRUE, width = 0.7) +
  geom_col(aes(alpha = group, fill=region), data = df3_neg, position = "dodge", na.rm = TRUE, width = 0.7) +
  scale_fill_manual(values=c("#CC6600", "#333BFF")) +
  scale_alpha_manual(values = c(T2 = .2, T1 = 1)) +
  guides(alpha = FALSE) + theme(legend.position="bottom", legend.title = element_blank())
#p2 + annotate("text", x =150, y = 3, label = "Annotation &", vjust = -5, fontface = 2) + annotate("text", x =150, y = 3, label = "Annotation 2", vjust = -2, size=6) 
ggarrange(p2, stable.p, ncol = 2, nrow = 1, heights = c(1, 1))

这是一个有点复杂的例子,但我想测试这个详细的例子? 是否可以使用 ggplot 进行设置?

在此处输入图像描述

提前致谢!

如果将position = "dodge"替换为position = position_dodge(0.8) ,则可以使用参数指定组的宽度。

0.7 将对应于您现有的版本。 1 表示每个条与组之间的空间量与组之间的空间量相同。 所以 0.8 或 0.9 可能就在你想要的附近。

0.8

在此处输入图像描述

0.9

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM