ggplot2中的斜体和换行符

时间:2019-02-28 18:38:05

标签: r ggplot2

我正在尝试使用斜体 n 和使用scale_x_discrete的换行符来适应标题。这是使用mpg的示例。无需尝试使用斜体,制造商的名称就显示在对勾下方,而n =行则集中在其下方。这就是我想要的。我无法重现带有bquote或表达的斜体。由于斜体 n 必须是字幕的最常用符号之一,因此我认为我遗漏了一些显而易见的内容。有人可以帮忙吗?

mpg2<- subset(mpg, manufacturer %in% c("audi", "toyota"))
mpg3<- subset(mpg2, class %in% c("compact", "midsize"))

cbp <- c("#E69F00", "#56B4E9")
xsub1 <-bquote(paste("Audi\n", italic("n"), " = 18 (15, 3)"))
xsub2 <-bquote(paste("Toyota\n", italic("n"), " = 19 (12, 7)"))


ggplot (mpg3, aes (x=manufacturer, y=hwy, colour=class))+
  geom_boxplot()+
  labs (colour = NULL)+
  xlab("")+
  ylab("highway mpg")+
  scale_colour_manual (labels = c ("compact","midsize"),
                        values = c(cbp))+
  scale_x_discrete(labels=c(xsub1, xsub2)) +
  theme (legend.position = "bottom")

1 个答案:

答案 0 :(得分:3)

您可以使用atop()功能。

mpg2 <- subset(mpg, manufacturer %in% c("audi", "toyota"))
mpg3 <- subset(mpg2, class %in% c("compact", "midsize"))

cbp <- c("#E69F00", "#56B4E9")

xsub1 <- ~ atop(paste("Audi"), paste(italic("n"), " = 18 (15, 3)"))
xsub2 <- ~ atop(paste("Toyota"), paste(italic("n"), " = 19 (12, 7)"))

ggplot(mpg3, aes (x = manufacturer, y = hwy, colour=class))+
  geom_boxplot()+
  labs (colour = NULL)+
  xlab("")+
  ylab("highway mpg")+
  scale_colour_manual(labels = c("compact","midsize"), values = c(cbp))+
  scale_x_discrete(labels = c(xsub1, xsub2)) +
  theme (legend.position = "bottom")

enter image description here

解决方案来自@Jaap