r - 在 Ggplot2 中仅设置某些刻度线
问题描述
我想重新创建下面的图,它只在行首和行尾的 y 和 x 轴上显示刻度线。 情节的图片。到目前为止,我有以下代码:
elevation_plot <- StradeBianche%>%
ggplot(aes(x = `Accumulated Distance in Km`))+
geom_area(aes(y = elevation), fill = "grey")+
coord_cartesian(ylim = c(100,500))+
scale_y_continuous(expand = c(0,0), limits = c(0, 500), labels = label_number(suffix = " m"))+
scale_x_continuous(expand = c(0,0), breaks = seq(0, 180, 20), labels = label_number(suffix = ".0 km"))+
theme(panel.grid.minor = element_blank())+
theme(panel.grid.major = element_blank())+
theme(panel.background = element_rect(fill = "white"))+
theme(panel.border = element_blank())+
theme(axis.title = element_blank())+
theme(axis.ticks = element_blank())
结果是这样的: 结果图片。它非常接近,但仍然缺少刻度......我可以删除所有轴刻度或不删除。但是如果不删除沿轴的 x 和 y 值,我无法设法仅设置某些轴刻度。
任何帮助是极大的赞赏!
解决方案
如果将geom_segment()
s 放置在正确的坐标处并关闭数据的裁剪,则可以模仿刻度行为。缺点是您不能以绝对单位将分段端点相对于第一个端点放置,因此您必须摆弄偏移量和文本边距。下面的例子:
library(ggplot2)
xlim <- c(1, 5)
ylim <- c(4, 8)
offset <- 0.05
seg <- data.frame(
x = xlim[c(1,2,1,1)],
xend = xlim[c(1,2,1,1)] - c(0, 0, offset, offset),
y = ylim[c(1,1,2,1)],
yend = ylim[c(1,1,2,1)] - c(offset, offset, 0, 0)
)
ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point(aes(colour = Species)) +
geom_segment(data = seg, aes(x = x, y = y, xend = xend, yend = yend)) +
coord_cartesian(clip = "off",
xlim = xlim,
ylim = ylim,
expand = FALSE) +
theme(axis.ticks = element_blank(),
axis.line = element_line(),
axis.text.x = element_text(margin = margin(t = 8)),
axis.text.y = element_text(margin = margin(r = 8)))
由reprex 包于 2021-03-25 创建(v1.0.0)
推荐阅读
- time - 为什么我的 Unix 时间解析不一致?
- angular - 通过 {emitEvent: false} 通知控件更改
- html - 如何为整个区域应用背景颜色而不仅仅是文本
- docker - 在 docker-compose 中运行容器时使用当前用户
- c++ - 为什么通过引用传递给函数的变量不会立即改变其值?
- graphics - 如何制作网状歧管
- r - as.POSIXct 没有解释日期 19/10/2008
- mysql - CPanel SQLSTATE[HY000] [1045] 拒绝用户访问
- selenium - 使用 selenium-webdriver 和 jest 检查元素的消失
- java - Java:如何从 Maven 故障安全插件访问元文件信息?