用不同的颜色定制ggplot2轴标签 [英] customize ggplot2 axis labels with different colors

查看:1079
本文介绍了用不同的颜色定制ggplot2轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从ggplot2创建的基本条形图。 y变量包含正值和负值,大约一半的值是负值。我想自定义轴标签,以便当相应x因子的y值为负数时,其标签为红色。这是一个可重现的例子:

I have a basic bar graph I've created from ggplot2. The y variable contains both positive and negative values and about half the vector of values are negative. I would like to customize the axis labels such that when the y value of that corresponding x factor is a negative, its label is red. Here's a reproducible example:

#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"))

我需要的是一种将c,e和f的标签颜色更改为我选择的颜色的方法。我尝试切换主题(aes(axis.text.x = element_text(color = Air_pricier))),但是这产生了一个错误。

What I need is a way to change the label colors of "c", "e", and "f" to the color of my choosing. I tried toggling theme(aes(axis.text.x=element_text(colour=Air_pricier))) but that produced an error. Thanks in advance.

推荐答案

您可以向 axis.text.x theme()选项:

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))

这篇关于用不同的颜色定制ggplot2轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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