r - 将 geom_vline 扩展到绘图之外
问题描述
我正在尝试将我的 ggplot 图中的 geom_vline 线扩展到绘图空间之外并进入轴区域。这样做的目的是让这些线分隔轴标签,以便它可以与旁边的另一个图对齐(见下文)。
一些简短的示例代码(我有更多行,因此需要水平线来保持直线):
library(ggplot2)
library(cowplot)
library(dplyr)
#play data set
cars.data <- mtcars %>%
mutate(car_name = rownames(mtcars)) %>%
slice(1:6)
#I would like vlines to be extend in this plot
p1 <- ggplot(cars.data, aes(x = car_name, y = hp)) +
geom_point() +
scale_x_discrete(position = "top") +
coord_flip() +
geom_vline(aes(xintercept = seq(1.5, 6.5, 1)), color = "gray60") +
xlab("")
p2 <- ggplot(cars.data, aes(y = car_name, x = 1)) +
geom_text(aes(label = disp)) +
xlab("disp") +
geom_hline(aes(yintercept = seq(1.5, 6.5, 1)), color = "gray60")+
theme(axis.title.y = element_blank(),
axis.title.x = element_text(vjust = 0.5, angle = 30),
axis.text = element_blank(),
axis.line = element_blank(),
axis.ticks = element_blank(),
panel.background = element_rect(fill = "gray90"))
plot_grid(p1, p2, rel_widths = c(1,0.2))
我正在寻找的是扩展线,p1
以便它们在地块之间继续,几乎就像一个绘图表混合体。我试过clip = "off"
了,但似乎没有奏效。
解决方案
您必须自己绘制线条,以确保在您设置clip = "off"
. 我在geom_segment()
这里使用并手动设置坐标中的限制。
您还需要对齐两个图plot_grid()
以确保一切正常。
library(ggplot2)
library(cowplot)
library(dplyr)
#play data set
cars.data <- mtcars %>%
mutate(car_name = rownames(mtcars)) %>%
slice(1:6)
p1 <- ggplot(cars.data, aes(x = car_name, y = hp)) +
geom_point() +
scale_x_discrete(
name = NULL,
position = "top"
) +
scale_y_continuous(expand = c(0, 0)) +
coord_flip(clip = "off", ylim = c(80, 180)) +
geom_segment(
data = data.frame(x = seq(1.5, 6.5, 1), ymin = 80, ymax = 240),
aes(x = x, xend = x, y = ymin, yend = ymax),
inherit.aes = FALSE,
color = "gray60"
) +
xlab(NULL) +
theme_cowplot()
p2 <- ggplot(cars.data, aes(y = car_name, x = 1)) +
geom_text(aes(label = disp)) +
xlab("disp") +
geom_hline(aes(yintercept = seq(1.5, 6.5, 1)), color = "gray60") +
theme_cowplot() +
theme(
axis.title.y = element_blank(),
axis.title.x = element_text(vjust = 0.5, angle = 30),
axis.text = element_blank(),
axis.line = element_blank(),
axis.ticks = element_blank(),
panel.background = element_rect(fill = "gray90"),
plot.margin = margin(7, 7, 7, 0)
)
plot_grid(p1, p2, rel_widths = c(1,0.2), align = "h", axis = "bt")
由reprex 包(v0.3.0)于 2019 年 12 月 2 日创建
推荐阅读
- json - Jinja 通过 Ansible URI 模块模板化 Json GraphQL 查询
- android - Alt Beacon Library、RegionBootstrap 和 BeaconManager 同时工作
- macos - 无法在 MAC(Mojave)上运行 Qt 安装程序应用程序
- python - 如何防止错误消息显示在屏幕上
- angular - 角度步进器,一步显示多个组件
- python - 是否可以使用命名变量对 Pyspark 数据框进行通配符过滤?
- ajax - 对 RestControler Spring 的 Ajax 请求返回 403 错误
- reporting-services - 如何为系列组获取折线图的百分比值?/如何通过 sql 表绘制图形?
- asp.net-core - 在 MVC 控制器中提交按钮操作
- java - 未调用 Spring 和自定义默认 HostnameVerifier