2017-12-28 35 views
5

凡例のタイトルが長い場合、凡例のタイトルを中央揃えで凡例キーに対して相対的に苦労しています。短いタイトルのために働く質問a year agoからですが、それは長いもののために働くようには思われません。短い凡例タイトル最初長い凡例タイトルのためのggplot2の中央揃えの凡例タイトルと凡例キー

例:予想通り

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) 

enter image description here

すべては、凡例のタイトル凡例のキー上にセンタリングされています。私たちは、テキストが凡例マーカーに対する自身に合わせ、中心ですが、ないことがわかります

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) 

enter image description here

:長い凡例タイトル

今と同じ。私はlegend.justification = "center"のような他のテーマのオプションを変更しようとしましたが、凡例ボックスの一番左の位置からキーを移動させるようなものはありません。

コメントのカップル:

  • 私は数日前からv2.2.1.9000、ggplot2の開発バージョンを実行していますよ。

  • 具体的には、連続カラースケールパレットのソリューションが必要です。

答えて

4

ソースコードを変更する必要があります。現在、ビューポート(gtable)にはcomputes the widths for the title grob and the bar+labelsleft-justifies the bar+labelsです。これはハードコードされています。

+0

おかげで、それは私が心配していたものです。私は問題を開くことから始めます。 –

+0

問題には独自の問題があります。あなたがそれをやり過ごした場合、[不幸な結果](https://github.com/tidyverse/ggplot2/issues/816#issuecomment-35949082)があるかもしれません。 – baptiste

+0

ああ、私は、プルの要求が来る必要があります参照してください。多分、別の日には、私はすぐに別のテーマパラメータを追加せずにこの問題を解決する方法を見ていません。 –

1

解決策が見つかりました。それはgrobツリーにいくつかの掘り出しを必要とし、複数の伝説がある場合はうまくいかないかもしれませんが、そうでなければ、何かがうまくいくまで合理的な解決策に見えます。

library(ggplot2) 
library(gtable) 
library(grid) 

p <- 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) 

# extract legend 
g <- ggplotGrob(p) 
grobs <- g$grobs 
legend_index <- which(sapply(grobs, function(x) x$name) == "guide-box") 
legend <- grobs[[legend_index]] 

# extract guides table 
guides_index <- which(sapply(legend$grobs, function(x) x$name) == "layout") 
guides <- legend$grobs[[guides_index]] 

# add extra column for spacing 
# guides$width[5] is the extra spacing from the end of the legend text 
# to the end of the legend title. If we instead distribute it 50:50 on 
# both sides, we get a centered legend 
guides <- gtable_add_cols(guides, 0.5*guides$width[5], 1) 
guides$widths[6] <- guides$widths[2] 
title_index <- guides$layout$name == "title" 
guides$layout$l[title_index] <- 2 

# reconstruct legend and write back 
legend$grobs[[guides_index]] <- guides 
g$grobs[[legend_index]] <- legend 

grid.newpage() 
grid.draw(g) 

enter image description here

関連する問題