首页 > 解决方案 > How to change the label color of hline in ggplot2

问题描述

Here is my data:

month=c("Jan","Feb","Mar","Apr","May","Jun")
rate=c(70,80,90,85,88,76) 
data=data.frame(month,rate)
data$month=factor(data$month, levels = month.abb)

I created the y label as below:

library(ggplot2)
ggplot(data,aes(x=month,y=rate)) + 
  geom_point(aes(x=month,y=rate), color="#00BFC4", size=2) +
  geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = rate, group=1), color="#00BFC4", size=1) + 
  geom_hline(aes(yintercept=87), color = "#F8766D", linetype = "dashed", size = 0.5) +
  scale_y_continuous(breaks = sort(c(seq(0,100,20),87)), 
                     labels = paste0(sort(c(seq(0,100,20),87)),"%")) + 
  expand_limits(y = c(0,100)) +
  labs(y = NULL, x= NULL) 

enter image description here

As you can see, the hline label at 87% is in grey color, I'd like to know how to change the color into the "#F8766D" as the same color of the dashed line.

In addition, I'd like to know how to change the position of 87% to the right side of the picture (i.e how to modify the position as a second y axis) and change the label color at the same time. Thanks!

标签: rggplot2

解决方案


要将 hline 标签的颜色更改为主轴:

ylabel=sort(c(seq(0,100,20),87))
color1 <- ifelse(ylabel == 87, "#F8766D", "grey30")

library(ggplot2)
ggplot(data,aes(x=month,y=rate)) + 
  geom_point(aes(x=month,y=rate), color="#00BFC4", size=2) +
  geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = rate, group=1), color="#00BFC4", size=1) + 
  geom_hline(aes(yintercept=87), color = "#F8766D", linetype = "dashed", size = 0.5) +
  scale_y_continuous(breaks = sort(c(seq(0,100,20),87)), 
                     labels = paste0(sort(c(seq(0,100,20),87)),"%")) + 
  expand_limits(y = c(0,100)) +
  labs(y = NULL, x= NULL) +
  theme(axis.ticks.y = element_line(color = color1),
        axis.text.y=element_text(color=color1))

在此处输入图像描述

要将 hline 标签的颜色更改为第二个轴:

ggplot(data,aes(x=month,y=rate)) + 
  geom_point(aes(x=month,y=rate), color="#00BFC4", size=2) +
  geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = rate, group=1), color="#00BFC4", size=1) + 
  geom_hline(aes(yintercept=87), color = "#F8766D", linetype = "dashed", size = 0.5) +
  scale_y_continuous(breaks = seq(0,100,20), 
                     labels = paste0(seq(0,100,20),"%"),
                     sec.axis = sec_axis(trans=~., breaks=87, labels=paste0(87,"%"))) + 
  expand_limits(y = c(0,100)) +
  labs(y = NULL, x= NULL) +
  theme(axis.ticks.y.right = element_line(color = "#F8766D"),
        axis.text.y.right = element_text(color = "#F8766D"))

在此处输入图像描述


推荐阅读