rm(list = ls())
###############################input data
library(scales)
library(ggplot2)
df <- data.frame(PCP = c("AA","BB","CC","DD", "EE"),
percentage = c(.5,.6,.7,.8,.9),
col = c("red","gray","pink","green","blue"))
df
## PCP percentage col
## 1 AA 0.5 red
## 2 BB 0.6 gray
## 3 CC 0.7 pink
## 4 DD 0.8 green
## 5 EE 0.9 blue
#######################
df$PCP <- factor(df$PCP, levels = df$PCP[5:1])
ggplot(df,aes(x=PCP, y=percentage)) +
geom_col(fill = "gray60") +
coord_flip() +
labs(x ="PCP Name",
y = "Percentage of Gap Closures",
title = "TOP 10 PCPs") +
scale_y_continuous(labels = percent_format(), limits=c(0,1)) +
theme(legend.position = "none",
panel.grid = element_blank(),
panel.background = element_blank(),
text = element_text(size=15),
plot.caption = element_text(hjust = 0, face= "italic"),
axis.text.y = element_text(colour = df$col))
## Warning: Vectorized input to `element_text()` is not officially supported.
## Results may be unexpected or may change in future versions of ggplot2.

###########################
ggplot(df,aes(x=PCP, y=percentage)) +
geom_col(fill = "gray60") +
coord_flip() +
labs(x ="PCP Name",
y = "Percentage of Gap Closures",
title = "TOP 10 PCPs") +
scale_y_continuous(labels = percent_format(), limits=c(0,1)) +
theme(legend.position = "none",
panel.grid = element_blank(),
panel.background = element_blank(),
text = element_text(size=15),
plot.caption = element_text(hjust = 0, face= "italic"),
axis.text.y = element_text(colour = df$col[as.integer(df$PCP)]))
## Warning: Vectorized input to `element_text()` is not officially supported.
## Results may be unexpected or may change in future versions of ggplot2.

df$col[as.integer(df$PCP)]
## [1] "blue" "green" "pink" "gray" "red"
##############
#ggplot change the x axis label colors dynamically
#https://stackoverflow.com/questions/59826366/ggplot-change-the-x-axis-label-colors-dynamically