我想在 y 軸上的某些標簽周圍畫一個紅色圓圈。我有以下資料和代碼來制作繪圖:
data <- structure(list(group = c("1", "1", "1", "2", "2", "2",
"3", "3", "3"), word = c("headache",
"computer", "window", "window", "plant", "coffee", "headache", "sky",
"computer"), n = c(115L, 125L, 130L, 132L, 134L, 157L,
195L, 209L, 215L), row = 1:9), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -9L))
#Define some colors to use throughout
my_colors <- c("#FFDBCE", "#8CAEAE", "#beb6d7")
wordfrequencyplot <- data %>%
ggplot(aes(row, n, fill =as.factor(group))) #as factor primetype to make it discrete
geom_col(show.legend = F)
labs(x = NULL, y = "Word Count")
facet_wrap(~group, scales = "free_y","fixed_x")
scale_x_continuous( # This handles replacement of row
breaks = data$row, # notice need to reuse data frame
labels = data$word)
scale_fill_manual(values = my_colors)
coord_flip()
theme_bw()
我想在 y 軸上圍繞第 2 組中的“咖啡”和“植物”以及第 3 組中的“天空”畫圈。
uj5u.com熱心網友回復:
與@Andrew Gillreath-Brown 發布的解決方案非常相似的解決方案是使用cowplot包在原始圖上繪制圓圈。但是,您需要使用 的 x 和 y 值circleGrob來獲得所需的輸出。
library(cowplot)
library(grid)
# Draw circles as Grob
g <- circleGrob(x = c(0.38, 0.38, 0.73),
y = c(0.51, 0.77, 0.51),
r = 0.05,
gp = gpar(fill = "transparent",
col = "red",
lwd = 3))
# Use ggdraw to add the circles over the original plot
ggdraw(wordfrequencyplot)
# Draw circles Grob
draw_grob(g)

uj5u.com熱心網友回復:
可能有更好的方法可以做到這一點,但您可以將ggplot物件轉換為grob,然后使用grid.circlefromgrid來放置圓圈。
library(grid)
library(ggplotify)
library(ggplot2)
wordfrequencyplot_grob <- as.grob(wordfrequencyplot)
plot(wordfrequencyplot_grob)
grid::grid.circle(x=0.365, y=0.784, r=0.039, default.units="npc", name=NULL,
gp=gpar(fill = NA, col = "red", lwd = 2), draw=TRUE, vp=NULL)
grid::grid.circle(x=0.367, y=0.511, r=0.034, default.units="npc", name=NULL,
gp=gpar(fill = NA, col = "red", lwd = 2), draw=TRUE, vp=NULL)
grid::grid.circle(x=0.706, y=0.511, r=0.026, default.units="npc", name=NULL,
gp=gpar(fill = NA, col = "red", lwd = 2), draw=TRUE, vp=NULL)
輸出

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407007.html
標籤:
