我想在呼叫自定義函式時為特定軸刻度標簽著色。例如,看這張圖:
library(ggplot2)
ggplot(mtcars, aes(x = as.factor(cyl)))
geom_bar()

創建于 2022-11-15,使用reprex v2.0.2
我想用“紅色”為 xaxis 刻度標簽 6 上色。你可以像這樣給axis.text.xwith上色:element_texttheme
library(ggplot2)
ggplot(mtcars, aes(x = as.factor(cyl)))
geom_bar()
theme(axis.text.x = element_text(colour = c("black", "red", 'black')))

創建于 2022-11-15,使用reprex v2.0.2
但當然,這并不是真正自動和流暢的。這是自定義函式的起點:
color_axis_tick_label <- function(df, xaxis, xaxistick) {
ggplot(df, aes(x = as.factor({{xaxis}})))
geom_bar()
}
有誰知道是否可以以更自動的方式執行此操作?
uj5u.com熱心網友回復:
一種選擇是使用ggtext::element_markdown自定義函式作為labels比例引數:
library(ggplot2)
library(ggtext)
color_axis_tick_label <- function(df, xaxis, xaxistick) {
ggplot(df, aes(x = as.factor({{ xaxis }})))
scale_x_discrete(
labels = ~ ifelse(.x %in% xaxistick,
paste0("<span style='color: red'>", .x, "</span>"), .x
)
)
geom_bar()
theme(axis.text.x = ggtext::element_markdown())
}
color_axis_tick_label(mtcars, cyl, 6)

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/534933.html
標籤:r图表2
