以编程方式处理ggplot2轴文本面 [英] Handle ggplot2 axis text face programmatically

查看:64
本文介绍了以编程方式处理ggplot2轴文本面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(x发布到 community.rstudio. com )

我想知道是否可以通过编程方式更改ggplot2中的轴文本,或者是否有某些本机方式可以在ggplot2中执行此操作.在此reprex中,我的想法是我想将绝对值x超过1.5的变量y的轴文本加粗.我可以通过theme()手动添加它,效果很好:

I'm wondering if it's possible to change the axis text in ggplot2 programatically or if there is some native way to do this in ggplot2. In this reprex, the idea is that I want to bold the axis text of a variable y that has an absolute value of x over 1.5. I can add it in manually via theme(), and that works fine:


library(ggplot2)
library(dplyr)
library(forcats)

set.seed(2939)
df <- data.frame(x = rnorm(15), y = paste0("y", 1:15), group = rep(1:3, 5))

df <- mutate(df, big_number = abs(x) > 1.5, face = ifelse(big_number, "bold", 
  "plain"))

p <- ggplot(df, aes(x = x, y = fct_inorder(y), col = big_number)) + geom_point() + 
  theme(axis.text.y = element_text(face = df$face))

p

无小平面的图1

但是,如果我按group进行操作,则y将重新排序,并且ggplot2不知道face如何连接到df并因此连接到y,因此它只是以与第一个情节.

But if I facet it by group, y gets reordered and ggplot2 has no idea how face is connected to df and thus y, so it just bolds in the same order as the first plot.

p + facet_grid(group ~ .)

具有刻面的图2

如果我对每个表使用不同的比例,那就更糟了.

And it's worse if I use a different scale for each.

p + facet_grid(group ~ ., scales = "free")

具有小平面和不同比例的图3

Plot 3 with facets and different scales

您怎么看?是否有一种通用的方法可以在这里始终如一地工作?

What do you think? Is there a general way to handle this that would work consistently here?

推荐答案

想法:不要更改主题,请更改y轴标签.为每个具有if/else条件的y创建一个调用,并使用parse对其进行解析.

Idea: Don't change theme, change y-axis labels. Create a call for every y with if/else condition and parse it with parse.

不是最优雅的解决方案(使用for循环),但是可以工作(需要循环,因为bquoteifelse中不起作用).尝试使用多个表达式时,我总是很困惑(有关这里).

Not the most elegant solution (using for loop), but works (need loop as bquote doesn't work with ifelse). I always get confused when trying to work with multiple expressions (more on that here).

代码:

# Create data
library(tidyverse)
set.seed(2939)
df <- data.frame(x = rnorm(15), y = paste0("y", 1:15), group = rep(1:3, 5)) %>%
    mutate(yF = fct_inorder(y),
           big_number = abs(x) > 1.5)

# Expressions for y-axis
# ifelse doesn't work
# ifelse(df$big_number, bquote(bold(1)), bquote(plain(2)))
yExp <- c() # Ignore terrible way of concatenating 
for(i in 1:nrow(df)) {
    if (df$big_number[i]) {
        yExp <- c(yExp, bquote(bold(.(as.character(df$yF[i])))))
    } else {
        yExp <- c(yExp, bquote(plain(.(as.character(df$yF[i])))))
    }
}

# Plot with facets
ggplot(df, aes(x, yF, col = big_number)) + 
    geom_point() +
    scale_y_discrete(breaks = levels(df$yF), 
                     labels = parse(text = yExp)) +
    facet_grid(group ~ ., scales = "free")

结果:

这篇关于以编程方式处理ggplot2轴文本面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆