【问题标题】:Conditional formatting of axis text using ggplot2使用 ggplot2 对轴文本进行条件格式设置
【发布时间】:2019-08-26 02:28:17
【问题描述】:

我正在尝试格式化轴文本以反映所使用的相同组 填充下图中的几何图形。为填充参数选择配色方案 在 aes() 中,导致 a 和 b、c 之间的颜色不同。中使用的 ifelse 语句 但是 element_text() 不会产生正确的颜色格式。

library(ggplot2)

# Make some data (emulating melted format)
df <- cbind.data.frame(c('a', 'a', 'a', 'b', 'c'), 
                       c(5, 5, 5, 15, 45), 
                       c(1, 1, 1, 0, 0))
names(df) <- c('variable', 'value', 'col')

# Conditional statement to be used in plot
con <- ifelse(df$col == 1, 'red', 'green')

# Call to the plot included below
ggplot(df, aes(x = variable, y = value)) + 
  geom_bar(stat = "identity", aes(fill = col)) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = con))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您的con 变量有五个元素,其中前三个是“红色”:

    [1] "red"   "red"   "red"   "green" "green"
    

    由于只有三个轴标签,theme 使用前三个值,从而使所有标签变为红色。当con 的长度合适时,我们会得到想要的结果:

    con <- ifelse(unique(df$variable) == 'a', 'red', 'darkgreen')
    

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-29
      • 2020-04-29
      • 2020-04-28
      • 1970-01-01
      • 2011-12-29
      • 2020-12-19
      相关资源
      最近更新 更多