You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ggside中轴标题与图例相对主图居中对齐?

问题:ggside绘图中轴标题与图例的对齐及自动获取panel.scale值

背景

我正在使用ggside包将数据的等高线图与折线图绘制在同一幅图中,绘图功能正常,但x、y轴标题及图例的位置存在问题——这些元素(如图中黑线所示)相对于整个绘图区域(主图+侧边图)居中,而非相对主图对齐。

初始绘图代码:

rm(list = ls(all = TRUE))

if (!require("ggplot2")) install.packages("ggplot2")
if (!require("ggside")) install.packages("ggside")

# 获取数据

# 等高线数据
set.seed(230529)

z <- runif(n = 100, min = -5, max = 20)
x <- y <- seq(1, length(z)/10, 1)
tmp <- expand.grid(x, y)
x <- tmp[,1]
y <- tmp[,2]

df.1 <- data.frame(x, y)
df.1$z <- z
df.1$level <- as.numeric(df.1$z)

# 折线图数据
y <- runif(n = length(z)/10, min = -5, max = 20)
x <- seq(1, length(y), 1)

df.2 <- data.frame(x = x, y = y)

# 绘图
ggplot(df.1, aes(x = x, y = y)) +
  geom_contour(aes(z = z, color = after_stat(level))) + 
  geom_hline(yintercept = sum(range(x))/2) +
  geom_vline(xintercept = sum(range(x))/2) +
  theme(aspect.ratio = 1) +
  geom_xsideline(data = df.2, aes(x = x, y = y)) +
  geom_ysideline(data = df.2, aes(x = y, y = x), orientation = "y")

初始问题

ggside是否有选项可将轴标题、图例这类元素相对主图对齐?若没有,能否通过hjust等参数自动调整位置?

已尝试的解决方法(更新)

通过设置ggside.panel.scale,结合hjust和vjust参数可实现需求:

rm(list = ls(all = TRUE))

if (!require("ggplot2")) install.packages("ggplot2")
if (!require("ggside")) install.packages("ggside")

# 获取数据

# 等高线数据
set.seed(230529)

z <- runif(n = 100, min = -5, max = 20)
x <- y <- seq(1, length(z)/10, 1)
tmp <- expand.grid(x, y)
x <- tmp[,1]
y <- tmp[,2]

df.1 <- data.frame(x, y)
df.1$z <- z
df.1$level <- as.numeric(df.1$z)

# 折线图数据
y <- runif(n = length(z)/10, min = -5, max = 20)
x <- seq(1, length(y), 1)

df.2 <- data.frame(x = x, y = y)

# 绘图
ggplot(df.1, aes(x = x, y = y)) +
  geom_contour(aes(z = z, color = after_stat(level))) + 
  geom_hline(yintercept = sum(range(x))/2) +
  geom_vline(xintercept = sum(range(x))/2) +
  theme(axis.title.x = element_text(hjust = 0.4375),
        axis.title.y = element_text(vjust = 0.4375),
        legend.position = "right",
        legend.justification = c(1,0.4375),
        aspect.ratio = 1) +
  geom_xsideline(data = df.2, aes(x = x, y = y)) +
  geom_ysideline(data = df.2, aes(x = y, y = x), orientation = "y") +
  theme(ggside.panel.scale = 0.125,
        ggside.axis.text = element_blank(),
        ggside.axis.ticks = element_blank())

新问题

能否自动获取ggside.panel.scale的取值?


内容的提问来源于stack exchange,提问作者Excelsior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 11:42:54