我用ggplot2创建了一个基本的条形图.y变量包含正值和负值,大约一半的值向量为负值.我想定制轴标签,这样当对应x因子的y值为负时,其标签为红色.下面是一个可重复的例子:

#Create data
x <- c("a","b","c","d","e","f")
y <- c("10", "9","-10","11","-3","-15")
data <- data.frame(x, y)
data$y <- as.numeric(as.character(data$y))

data$category <- ifelse(as.numeric(data$y)<0, 0, 1)
data$category <- as.factor(data$category)

#Graph
library(cowplot) #theme
library(ggplot2)

ggplot(data, aes(x=x, y=y)) + 
  geom_bar(stat = "identity", aes(fill=category)) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  theme(axis.text.x = element_text(colour = "black"))

enter image description here

我需要的是一种将"c"、"e"和"f"的标签 colored颜色 更改为我 Select 的 colored颜色 的方法.我试着切换到theme(aes(axis.text.x=element_text(colour=Air_pricier))),但出现了一个错误.提前谢谢.

推荐答案

您可以为theme()axis.text.x选项提供 colored颜色 向量:

a <- ifelse(data$category == 0, "red", "blue")

ggplot(data, aes(x = x, y = y)) + 
    geom_bar(stat = "identity", aes(fill = category)) +
    theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = a))

enter image description here

R相关问答推荐

R通过字符串中的索引连接数据帧r

给定R中另一行中的值,如何插补缺失值

按块将载体转换为矩阵-reshape

以R为基数排列奇数个图

通过使用str_detect对具有相似字符串的组进行分组

在ggplot2中更改小提琴情节的顺序

如何从像glm这样的模型中提取系数表的相关性?

在使用bslb和bootstrap5时,有没有办法更改特定dt行的 colored颜色 ?

R Read.table函数无法对制表符分隔的数据正常工作

如何在R库GoogleDrive中完全删除预先授权的Google帐户?

Ggplot2中geom_tile的动态zoom

根据纬度和距离连接两个数据集

如何使用For-R循环在向量中找到一系列数字

如何计算每12行的平均数?

以不同于绘图中元素的方式对GG图图例进行排序

数值型数据与字符混合时如何进行绑定

有毒元素与表观遗传年龄的回归模型

填充图例什么时候会有点?

如何使用循环从R中的聚合函数创建列,而不会在名称中给出&q;$&q;?

分隔日期格式为2020年7月1日