geom_text two colors in R

2019-09-06 01:31发布

问题:

I have a ggplot with a geom_text():

geom_text(y = 4, aes(label = text))

The variable text has the following format:

number1-number2

I want to know if it is possible to define a color for the number1 and another color for number2 (example: red and green color)

Thanks!

回答1:

One way is if you have for example the label texts of number1 and number2 as separate columns in the data frame:

ggplot(data, aes(x,y)) + geom_text(label=data[,3], color="red", vjust=0) + geom_text(label=data[,4], color="blue", vjust=1)


回答2:

You may also try annotate:

# data for plot
df <- data.frame(x = 1:5, y = 1:5)

# data for annotation
no1 <- "number1"
no2 <- "number1"
x_annot <- 4
y_annot <- 5
dodge <- 0.3

ggplot(data = df, aes(x = x, y = y)) +
  geom_point() +
  annotate(geom = "text", x = c(x_annot - dodge, x_annot, x_annot + dodge), y = y_annot,
           label = c(no1, "-", no2),
           col = c("red", "black", "green")) + 
theme_classic()

I defined the labels and positions outside the annotate call, which possibly makes it easier to generate these variables more dynamically, e.g. if "number1" in fact could be calculated from the original data set, or positions be based on range of x and y.



标签: r ggplot2