在ggplot2中,我不知道如何增加图例项之间的差距。我已经从这些帖子1,2中读到了一些类似的问题,但它对我的案例不起作用。下面是我的代码,它生成附图。我想增加图例项之间的差距,如附图所示。任何帮助或提示将非常感激。谢谢。
我的代码:
## data:
df <- data.frame(supp=rep(c(" link ratio 1:1 ", " link ratio 1:2 ", " link ratio 1:3 ",
" link ratio 1:4 ", " link ratio 1:5 ", " link ratio 1:6 "),
each=7, ## number of bargroups
ordered = TRUE), ## nrows
test_X=rep(c("1.0", "1.2", "1.4", "1.6", "1.8", "2.0", "2.2"), 6), ## ncols
test_Y=c(
8, 9, 16, 18, 23, 28, 27,
14, 15, 27, 30, 38, 47, 47,
8, 8, 11, 15, 21, 25, 22,
12, 13, 23, 25, 33, 39, 39,
7, 8, 13, 13, 18, 24, 24,
10, 12, 19, 22, 27, 33, 33))
## reorder legend items
df$supp <- factor(df$supp, c(" link ratio 1:1 ", " link ratio 1:2 ", " link ratio 1:3 ",
" link ratio 1:4 ", " link ratio 1:5 ", " link ratio 1:6 "))
## libs
require(ggthemes)
require(ggplot2)
g<-ggplot(data=df, aes(clarity, x=test_X, y=test_Y, fill=supp)) +
geom_bar(width=0.75, stat="identity", position=position_dodge(width=0.75), colour="#000000", size=1.35) +
scale_fill_brewer(palette="Greens") +
theme_bw(base_size = 30, base_family = "") +
theme(panel.border = element_rect(fill = NA, colour = "black", size = 2.75), legend.position="top",
legend.title = element_blank(),
legend.key = element_rect(fill = NA, colour = "black"),
legend.key.width = unit(1.4, "cm"),
legend.key.height = unit(0.5, "cm"),
legend.margin = unit(0.65, "cm"),
legend.text = element_text(size = 55, face= "bold")
) + scale_y_continuous(expand = c(0,0), limits=c(0, 55))
g<-g + guides(fill=guide_legend(ncol=2, byrow = TRUE))
g<-g + labs(x = "Rate", y="#links")
print(g)
图:
我想要的数字:
答案 0 :(得分:2)
借助legend.spacing.x
和legend.spacing.y
,现在有一种简单的方法可以实现此目的:
library(ggplot2)
df <- data.frame(
supp = rep(c("link ratio 1:1", "link ratio 1:2", "link ratio 1:3",
"link ratio 1:4", "link ratio 1:5", "link ratio 1:6"),
each = 7, ordered = TRUE),
test_X = rep(c("1.0", "1.2", "1.4", "1.6", "1.8", "2.0", "2.2"), 6),
test_Y = c(8, 9, 16, 18, 23, 28, 27,
14, 15, 27, 30, 38, 47, 47,
8, 8, 11, 15, 21, 25, 22,
12, 13, 23, 25, 33, 39, 39,
7, 8, 13, 13, 18, 24, 24,
10, 12, 19, 22, 27, 33, 33)
)
g <- ggplot(data = df, aes(clarity, x = test_X, y = test_Y, fill = supp)) +
geom_bar(width = 0.75, stat = "identity",
position = position_dodge(width = 0.75),
colour = "#000000", size = 1.35) +
scale_fill_brewer(palette = "Greens") +
theme_bw(base_size = 30) +
theme(
panel.border = element_rect(fill = NA, colour = "black", size = 2.75), legend.position = "top",
legend.title = element_blank(),
legend.key = element_rect(fill = NA, colour = "black"),
legend.key.width = unit(1.4, "cm"),
legend.key.height = unit(0.5, "cm"),
legend.spacing.x = unit(0.5, 'cm'),
legend.spacing.y = unit(1.0, 'cm'),
legend.text = element_text(size = 55, face = "bold")
) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 55)) +
guides(fill = guide_legend(ncol = 2, byrow = TRUE)) +
labs(x = "Rate", y = "#links")
g
注意1:您不需要ggthemes
,也不需要重新排序图例项,因此我从代码中删除了它们。
注2:除了重新格式化外,我将您的代码保持原样,但是最好减少图例的大小(很多)。