【问题标题】:Add multiple level x-label in ggplot2在 ggplot2 中添加多级 x-label
【发布时间】:2021-09-09 20:14:49
【问题描述】:

如何在 ggplot 2 中的多行上放置 x 标签。我知道我会使用如下图所示的 mtext 在基础图中执行此操作,但是创建类似 x 轴的等效方法是什么ggplot2 中的标签?

最小工作示例:

# List containing the expressions for the x-axes
xaxeslist = list(bquote("Low" %<-% "Complexity" %->% "High"), 
               bquote("High" %<-% "Bias" %->% "Low"),
               bquote("Low" %<-% "Variance" %->% "High"))

# In base R one would use mtext to plot the desired x-label values
# mtext(do.call(expression, xaxeslist), side = 1, line = 2:4)


# Dummy values for working example
xval = seq(0, 100, by = 0.001)
yval = seq(0, 100, by = 0.001)
data <- data.frame("x"=xval,"y"=yval)

# Plot the desired output
b<-ggplot(data) +
  aes(x = x, y = y) +
  geom_line(size = 1L) +
  labs(
    x = do.call(expression, xaxeslist),
    y = "Y-value",
    title = "Title"
  ) +
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.y = element_blank(),
        axis.text.y = element_blank())

print(b)

我想操纵 x-label 使其落入上图的多行中,即xaxeslist 成为 xlabel。

【问题讨论】:

标签: r ggplot2 axis-labels


【解决方案1】:

atop 函数是一个答案,它使您可以毫无困难地在 xlabggplot 中使用两行表达式:

ggplot(data) +
    aes(x = x, y = y) +
    labs(x = expression(atop("Low" %<-% "Complexity" %->% "High",
                             "High" %<-% "Bias" %->% "Low"))
         )

但是,用这样的策略很难获得三行表达式,一种解决方案是:

ggplot(data) +
    aes(x = x, y = y) +
    labs(x = expression(atop(atop(textstyle("Low" %<-% "Complexity" %->% "High"),
                                 textstyle("High" %<-% "Bias" %->% "Low")),
                            "Low" %<-% "Variance" %->% "High")),
        y = "Y-value",
        title = "Title"
    )

虽然不是没有错误,因为第二行和第三行之间的空间太大!

【讨论】:

    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    相关资源
    最近更新 更多