[R] Colour for unique label with ggplot

Eric Berger er|cjberger @end|ng |rom gm@||@com
Thu Jun 20 10:03:09 CEST 2019


Hi Phil,

Try this

library(tidyverse)
# Test data
dta <- data.frame(dta_names=c("Series 1","Series 2","Series 3","Series 4"),
dta_values=c(0.5,1.3,-0.7,0.2))
dta$dta_names <- as.character(dta$dta_names) # convert from factor

*dta$labelColor <- c("black","red","black","black")*
# Bar chart
ggplot(dta,aes(x=dta_names,y=dta_values)) +
  geom_bar(stat="identity",fill="darkblue") +
  geom_bar(data=dta[2, ],stat="identity",aes(x=dta_names, y=dta_values),
           fill="red") +
  *theme(axis.text.y = element_text(colour=dta$labelColor)) +*
  labs(title = "Example bar chart") +
  coord_flip()

I did not know how to do this. I did a search on

ggplot format axis labels categorical data different each category

and the first result was the following URL which provided the necessary
information

https://stackoverflow.com/questions/38862303/customize-ggplot2-axis-labels-with-different-colors


HTH,
Eric


On Thu, Jun 20, 2019 at 4:24 AM <phil using philipsmith.ca> wrote:

> # RStudio version 1.1.463
> # sessionInfo()
> # R version 3.5.1 (2018-07-02)
> # Platform: x86_64-apple-darwin15.6.0 (64-bit)
> # Running under: macOS  10.14.5
>
> # I am constructing a bar chart using ggplot, as in the example below.
> # I want to highlight "Series 2" by colouring the bar red,
> # with the other bars coloured blue. That works.
> # I also want to colour the label "Series 2" (only) in red, but I have
> not
> # been able to find a way to do that.
> # Here is the example:
>
> library(tidyverse)
> # Test data
> dta <- data.frame(dta_names=c("Series 1","Series 2","Series 3","Series
> 4"),dta_values=c(0.5,1.3,-0.7,0.2))
> dta$dta_names <- as.character(dta$dta_names) # convert from factor
> # Bar chart
> ggplot(dta,aes(x=dta_names,y=dta_values)) +
>    geom_bar(stat="identity",fill="darkblue") +
>    geom_bar(data=dta[2, ],stat="identity",aes(x=dta_names, y=dta_values),
> fill="red") +
>    labs(title = "Example bar chart") +
>    coord_flip()
>
> # Any suggestions appreciated.
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list