是否可以在 ggplot 創建的帶有兩個圖例的圖形中控制一個相對于另一個的位置?
在下面的簡單圖形中,我試圖將“Normal”的圖例鍵與“Some color”圖例鍵垂直對齊。我希望圖形上的紅線與顏色條的中心高度相同。
下面的第一張圖片是我被卡住的地方。如果可以移動單個圖例,則下面的第二個影像是所需的結果。
下面提供了一個可重現的示例。在這種情況下,“正常”圖例的標題為空白,我僅使用標簽。我嘗試在legend_guide 中使用label.vjust=0.5(或1)選項,但這是一個小的垂直移動,紅線不會隨之移動。


一個例子:
library(ggplot2)
library(dplyr)
tt <- tibble(a=runif(15))
tt <- tt %>% mutate(n=row_number())
tt %>% ggplot()
geom_col( aes(x=n,y=a,fill=a))
geom_line(aes(x=n,y=a,color='Normal'),size=1)
theme_bw()
scale_color_manual(values=c('Normal'='red'))
labs(title='A Title',
x='Some Numbers',
y='The Y-Axis',
color = '',
fill='Some Color')
theme(plot.title = element_text(hjust=0.5),
axis.title.x = element_blank(),
legend.title = element_text(size=13,face='bold'),
legend.text = element_text(size=13,face='bold'),
legend.direction = "horizontal",
legend.position = "bottom",
legend.key.width=unit(1.0,"cm"),
legend.key.height=unit(.25,"cm"),
legend.box.background = element_blank(),
legend.justification = "center",
legend.margin = margin(0.,0.,0.,0., unit="cm"),
legend.background = element_blank(),
plot.margin = margin(0.5, 0, 0, 0, "cm"))
guides(fill = guide_colorbar(title.position = "top",
title.hjust = 0.5),
color = guide_legend(title.position = "top",
label.vjust = 0.5, #centres the title horizontally
label.position = "top",
order=1)
)
感謝您的任何建議。
uj5u.com熱心網友回復:
有點黑客,但如果你想微調這樣的情節,我想幾乎沒有其他方法(或者你制作一個假傳奇)。
為您的審美分配值“”(空間!)并將顏色映射到此。因此,圖例將沒有可見的標簽,您可以將其放置在“底部”。
PS 你應該總是set.seed在運行采樣函式之前。
library(tidyverse)
tt <- tibble(a=runif(15))
tt <- tt %>% mutate(n=row_number())
data.frame()
#> data frame with 0 columns and 0 rows
tt %>% ggplot()
geom_col( aes(x=n,y=a,fill=a))
geom_line(aes(x=n,y=a, color = " "), size=1)
theme_bw()
labs(title='A Title',
x='Some Numbers',
y='The Y-Axis',
fill='Some Color',
color = "Normal")
theme(legend.direction = "horizontal",
legend.position = "bottom")
scale_color_manual(values=c(' '='red'))
guides(fill = guide_colorbar(title.position = "top",
title.hjust = 0.5),
color = guide_legend(title.position = "top",
label.vjust = 0.5, #centres the title horizontally
label.position = "bottom",
order=1)
)

由reprex 包(v2.0.1)于 2021 年 11 月 17 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/360793.html
