r - 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)
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!
解决方案
要将 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"))
推荐阅读
- r - 在 R 中使用 tidyverse 进行汇总后保留列
- jmeter - 如何在gitlab中读取jmeter结果
- google-bigquery - 从 gSheet 生成的 BigQuery 表无法通过 JDBC 驱动程序访问
- python - 替换 Pandas 列中的字符
- angular - 我们可以在Angular10的@Injectable服务中使用@viewChild吗
- javascript - 有条件地在 package.json 中安装不同版本的 npm 包
- c - C中字符和字符串函数的二维数组
- javascript - 使用 ngClass 函数将样式应用于字符串字符
- python - 无法使用 pymodbus 读取寄存器值
- php - 如何找到班级中的最高平均分