简体   繁体   English

ggplot中图例项的间距

[英]Spacing of Legend Items in ggplot

I want to know how to increase the space between legend items in ggplot.我想知道如何增加 ggplot 中图例项之间的空间。 This comes in handy when you have more involved plots and the viewer needs a clear legend of a color gradient, which is sometimes hard to see when you don't have enough whitespace between the parts of a color gradient.当您有更多涉及的绘图并且查看器需要颜色渐变的清晰图例时,这会派上用场,当您在颜色渐变的各个部分之间没有足够的空白时有时很难看到。

REPREX代表

data(iris)

iris$Sepal.Length.cut<-cut(iris$Sepal.Length, breaks=seq(4,8,1), labels=c("here","and here","here too", "here three"))

iris.grad<-colorRampPalette(c("darkgoldenrod","darkgoldenrod4"))
iris.col<-iris.grad(4)
names(iris.col)<-levels(iris$Sepal.Length.cut)

ggplot(iris)+
  geom_bar(aes(x=Species,fill=Sepal.Length.cut), stat="count")+
  scale_fill_manual(values=iris.col, name="increase space \n where indicated")+
  theme(legend.spacing.y=unit(1.5,"lines"))

legend.spacing.y only increases the space between the title and the legend elements, increasing the key size doesn't get rid of the problem. legend.spacing.y 只增加标题和图例元素之间的间距,增加键大小并不能解决问题。 Interestingly enought this solution actually says it should and their reprex works for me... maybe its the difference between bars and points?有趣的是, 这个解决方案实际上说它应该和他们的 reprex 对我有用......也许它是条形图和点数之间的区别?

You can do this by specifying guide_legend(byrow = TRUE) before adding the spacing to your theme.您可以通过在将间距添加到主题之前指定guide_legend(byrow = TRUE)来做到这一点。

ggplot(iris) +
  geom_bar(aes(Species, fill = Sepal.Length.cut), stat = "count") +
  scale_fill_manual(values=iris.col, name = "increase space \n where indicated") +
  guides(fill = guide_legend(byrow = TRUE)) +
  theme(legend.spacing.y = unit(1.5, "lines"))

在此处输入图像描述

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

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