想象一下,有充分的理由要使多面ggplot中的每一行具有不同比例的mpg之类的变量。
如何将y轴标签放在小平面条标签内,以便非常清楚地由y轴标签而不是小平面描述单位?尤其欢迎修改下面代码的建议。
在您想象这种情况时,请也想像一下有充分的理由不将条带放在右边,而不要将双条带放在右边。 facet_wrap
会发生这种情况,并帮助我在“迷你”,“适度”和“肌肉”与y轴刻度之间获得“每加仑英里” :-)谢谢!
library(tidyverse)
data(mtcars)
mtcars %>%
mutate(transmission=c("real", "robot")[am+1]
, engine=c("mini", "modest", "muscle")[cyl/2-1]) %>%
ggplot(aes(wt*1000, mpg)) +
geom_point() +
facet_grid(engine ~ transmission, switch = "y", scales = "free") +
labs(x="vehicle weight (lbs)", y = "miles per gallon" ) +
theme_classic() +
theme( panel.spacing=unit(2, "lines")
, strip.placement.y = "outside"
, strip.background = element_blank()
, strip.text = element_text(face = "bold")
)
答案 0 :(得分:1)
我的方法: 在构面名称中包含单位,然后在名称和单位之间输入换行符。
library(tidyverse)
data(mtcars)
data <- mtcars %>%
mutate(transmission=c("real", "robot")[am+1]
, engine=c("mini", "modest", "muscle")[cyl/2-1]
# Later, we're going to insert the line break at a fixed point. To prepare:
# Change strings to a consistent width, one greater than the length of the longest string.
# In this case, the longest name is 6 characters long,
# so we'll pad the strings to be 7 characters wide.
, engine_l = str_pad(engine, width = 7, side = "right") %>%
# add unit to end of string
paste0("mpg")
,
# check that string length is consistent - should be 10 for all rows.
str_length(engine_l))
data %>%
ggplot(aes(wt*1000, mpg)) +
geom_point() +
facet_grid(engine_l ~ transmission, switch = "y", scales = "free",
# the labeller feature allows us to customize the facet labels.
# In this case, we enter a line break after 6 characters, the length of the longest name.
labeller = labeller(engine_l = label_wrap_gen(6))) +
# remove units from y axis label
labs(x="vehicle weight (lbs)", y = "" ) +
theme_classic() +
theme( panel.spacing=unit(2, "lines")
, strip.placement.y = "outside"
, strip.background = element_blank()
, strip.text = element_text(face = "bold")
)
我一直在尝试用“加仑/英里”代替“ mpg”,但现在还无法破解。也许其他人对此会有想法。 :)
此外,这是有关贴标签机的更多信息:https://ggplot2.tidyverse.org/reference/labeller.html