r - 在轴标签周围绘制彩色框

标签 r ggplot2

考虑这个简单的例子

library(tidyverse)
tibble(x = as.factor(c('good', 'neutral', 'bad')),
       y = as.factor(c('bad', 'neutral', 'bad'))) %>% 
  ggplot(aes(x = x, y = y)) + geom_point()

enter image description here

我想将 x 标签(goodneutralbad)放在不同颜色的框中。例如,good(在 x 轴和 y 轴上)将被包围在一个小绿色框内,依此类推。

我可以在 ggplot2 中这样做吗?

最佳答案

像这样?

tibble(x = as.factor(c('good', 'neutral', 'bad')),
y = as.factor(c('bad', 'neutral', 'bad'))) %>%
ggplot(aes(x = x, y = y)) + 
  geom_point() + 
  theme(axis.text.x = element_text(color = c('red', 'blue', 'green')))

你的情节:

your Plot

编辑

使用 grid 的另一种漂亮的 Ghetto 解决方案

tibble(x = as.factor(c('good', 'neutral', 'bad')),
y = as.factor(c('bad', 'neutral', 'bad'))) %>%
ggplot(aes(x = x, y = y)) + 
  geom_point()

grid::grid.polygon(x = c(.3,.3,.25,.25), y = c(.07,.04,.04,.07),gp = gpar(col = 'green', fill = 'green', alpha = .5))
grid::grid.polygon(x = c(.525,.525,.575,.575), y = c(.07,.04,.04,.07),gp = gpar(col = 'red', fill = 'red', alpha = .5))
grid::grid.polygon(x = c(.79,.79,.86,.86), y = c(.07,.04,.04,.07),gp = gpar(col = 'blue', fill = 'blue', alpha = .5))

the Ghetto way

关于r - 在轴标签周围绘制彩色框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56543485/

相关文章:

r - ggplot条形图中的水平白线

r - x 轴上的 ggplot 月度日期刻度使用天作为单位

r - 尽管+ geom_line() 图表中没有线条

r - 使用 gg voronoi 按因子着色时手动设置 Voronoi 图的颜色

r - 如何以 R "data.table"方式记录非重叠范围(或时间间隔)?

excel - 如何在 64 位 R 中写入 Excel 文件

r - 通过匹配第二个 data.table 中的列在 data.table 列中进行操作

r - 是否可以指定单个图的大小/布局以匹配 R 中的某个网格?

R:没有for循环的子集和排序大数据帧

list - 通过as.character()将列表强制转换为字符时,为什么会出现这种行为?