【问题标题】:ggplot2: Conditional formatting of x axis label in facet_gridggplot2:facet_grid 中 x 轴标签的条件格式
【发布时间】:2021-02-03 17:01:17
【问题描述】:

第一次发帖,如有冒犯请见谅。

数据(russ_defensive)看起来像这样

russ_defensive dataframe

此代码旨在创建一个由大写条件填充的堆叠条的 facet_grid,并根据行业是否具有防御性,将 axis.text.x 颜色设置为红色或黑色

library(dplyr)
library(ggplot2)

chart_foo <- ggplot(data = russ_defensive, aes(x = industry)) + 
facet_grid(~ sector, space = "free", scales="free") +  
geom_bar(stat="count") +  aes(fill = capitalisation) +
theme(axis.text.x = element_text(angle = 90, color = ifelse(russ_defensive$defensive_industries == "N", "red", "black")))

大约一半的行业是非防御性的(因此 russ_defensive$defensive_industries 为“N”),但是此代码仅将其中一个标签变为红色(请参阅here)并给出以下错误:

Warning message:
Vectorized input to `element_text()` is not officially supported.
Results may be unexpected or may change in future versions of ggplot2. 

这个/替代方法是否有一个简单的修复方法,可以根据数据集的列有条件地格式化标签?

感谢您的帮助,如果可重现的数据集有用,请告诉我。

【问题讨论】:

标签: r ggplot2 conditional-formatting facet facet-grid


【解决方案1】:

好吧,正如警告告诉您的那样,不建议使用矢量化主题输入来选择轴文本颜色(尽管许多人仍然尝试)。我相信这也是 ggtext 包背后的动机之一,您可以在其中使用 markdown 来样式化您的文本。下面,您将找到一个带有标准数据集的示例,我希望它可以很好地转化为您的示例。我们只是有条件地将颜色应用于某些 x 轴类别。

library(ggplot2)
library(ggtext)
#> Warning: package 'ggtext' was built under R version 4.0.3

df <- transform(mtcars, car = rownames(mtcars))[1:10,]

red_cars <- sample(df$car, 5)

df$car <- ifelse(
  df$car %in% red_cars,
  paste0("<span style='color:#FF0000'>", df$car, "</span>"),
  df$car
)


ggplot(df, aes(car, mpg)) +
  geom_col() +
  theme(axis.text.x = element_markdown(angle = 90))

reprex package (v1.0.0) 于 2021 年 2 月 3 日创建

更多示例,请参阅https://github.com/wilkelab/ggtext#markdown-in-theme-elements

【讨论】:

  • 这很完美!我想 ggtext 的不同之处在于它需要修改 df 中的实际值,然后再将其传递给 ggplot 但这绝对是最好的方法 - 谢谢! PS。 + scale_x_discrete(guide = guide_axis(angle = 90) 修复了标签偏离刻度的问题。
  • 嗯,是也不是,您肯定需要将颜色烘焙到标签中,但这不需要在数据中发生:您也可以在比例尺scale_x_discrete(labels = ifelse(...), ...) 中设置标签。
猜你喜欢
  • 2018-11-03
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
相关资源
最近更新 更多