geom_text two colors in R

2019-09-06 01:26发布

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!

标签: r ggplot2
2条回答
Fickle 薄情
2楼-- · 2019-09-06 01:58

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)
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-09-06 02:00

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.

查看更多
登录 后发表回答