将图例中的图例标题和图例中心对齐ggplot2中较长的图例标题 [英] Center-align legend title and legend keys in ggplot2 for long legend titles

查看:748
本文介绍了将图例中的图例标题和图例中心对齐ggplot2中较长的图例标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当图例标题很长时,我很难将图例的标题与图例中心对齐。有一个问题来自



一切都如预期,图例标题集中在图例关键字上方。



现在相同的长传说标题:

  ggplot(虹膜,aes(x = Sepal.Len gth,y = Sepal.Width,color = Petal.Width))+ geom_point(size = 3)+ 
scale_color_distiller(palette =YlGn,type =seq,direction = -1,
name =Long legend heading\\\
Should be centered)+
theme(legend.title.align = 0.5)



我们可以看到文本与中心对齐,但不是相对于传奇钥匙。我曾尝试修改其他主题选项,例如 legend.justification =center,但似乎没有将该按键从图例框中最左侧的位置移开。 / p>

一些评论:


  • 我正在运行开发版本ggplot2,v2.2.1.9000从几天前。

  • 我特别需要一个连续调色板的解决方案。



解决方案

您必须更改源代码。目前它计算标题grob和酒吧的宽度+标签左对齐酒吧+标签在视口(gtable)中。这是硬编码。


I am having a hard time making the title of a legend center-aligned relative to the legend keys when the legend title is long. There is a question from a year ago that works for short titles, but it doesn't seem to work for long ones.

Example, first with a short legend title:

library(ggplot2)
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Petal.Width)) + geom_point(size = 3) +
  scale_color_distiller(palette = "YlGn", type = "seq", direction = -1,
                        name = "A") +
  theme(legend.title.align = 0.5)

Everything is as expected, the legend title is centered above the legend key.

Now the same with a long legend title:

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Petal.Width)) + geom_point(size = 3) +
  scale_color_distiller(palette = "YlGn", type = "seq", direction = -1,
                        name = "Long legend heading\nShould be centered") +
  theme(legend.title.align = 0.5)

We can see that the text is center aligned to itself but not relative to the legend key. I have tried modifying other theme options, such as legend.justification = "center", but none seem to move the key from its left-most position in the legend box.

A couple of comments:

  • I'm running the development version of ggplot2, v2.2.1.9000 from a few days ago.

  • I specifically need a solution for a continuous colorscale palette.

解决方案

you'd have to change the source code. Currently it computes the widths for the title grob and the bar+labels, and left-justifies the bar+labels in the viewport (gtable). This is hard-coded.

这篇关于将图例中的图例标题和图例中心对齐ggplot2中较长的图例标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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