r - Draw geom_vline in discrete x axis
问题描述
I have trouble with drawing a vertical line in discrete (factor) levels in the x axis of my plot. in this solution it seems to working drawing vertical line with factor levels in ggplot2
but OTH this is not working with geom_tile
?
Basically, to remove the white space in the geom_tile I need to convert to numeric
x values to factor levels . But at the same time I want to draw a geom_vline
with a numeric value.
here is what is the problem
df <- data.frame(
x = rep(c(2, 5, 7, 9, 12), 2),
y = rep(c(1, 2), each = 5),
z = factor(rep(1:5, each = 2)))
library(ggplot2)
ggplot(df, aes(x, y)) +
geom_tile(aes(fill = z), colour = "grey50")+
geom_vline(aes(xintercept=6),linetype="dashed",colour="red",size=1)
to remove white space in geom_tile
need to convert to x to factor(x)
but when I do this geom_vline disappears!
解决方案
一种解决方案可能是修改您的数据 - 将其转换为pseudo-factor。
# Get rank of each x element within group
df$xRank <- ave(df$x, df$y, FUN = rank)
x y z xRank
1 2 1 1 1
2 5 1 1 2
3 7 1 2 3
4 9 1 2 4
5 12 1 3 5
6 2 2 3 1
7 5 2 4 2
8 7 2 4 3
9 9 2 5 4
10 12 2 5 5
绘制值等级而不是值并将 x 轴元素标记为原始值:
library(ggplot2)
ggplot(df, aes(xRank, y)) +
geom_tile(aes(fill = z), colour = "grey50") +
# On x axis put values as labels
scale_x_continuous(breaks = df$xRank, labels = df$x) +
# draw line at 2.5 (between second and third element)
geom_vline(aes(xintercept = 2.5),
linetype = "dashed", colour = "red",size = 1)
推荐阅读
- python - .one() 和 .scalar() 有什么区别
- python - 如何将 Django 模型布尔字段更新为真?
- reactjs - 如何使用 apollo Reactjs 客户端刷新 Firebase IdToken
- c - 如何分配 3d 字符指针数组?
- typescript - 泛型类型推断的打字稿泛型
- python - 无法并行化进程相互依赖的 Python 进程
- amazon-s3 - 如何修复没有在 django-oscar 中加载的仪表板字体
- c# - 减少 Firebird EntityFrameworkCore 中表别名的长度
- php - Adding icon to title bar
- android - 在 Linux Ubuntu 64 vm 上安装 Python-for-Android 时遇到问题