在ggplot2中,如何将标题移到左侧(不是左对齐——在左侧)?

问题描述 投票:0回答:2

我有一个情节,我希望标题位于左侧(不是左对齐)。换句话说,我希望它在“百分比”的左侧有一些空间。我读过的所有内容都只是展示了如何使其左对齐。任何帮助将不胜感激!

library(ggplot2)

# Sample data
data <- data.frame(
  satisfaction = c("Unhappy", "Neutral", "Happy"),
  percent = c(20, 40, 30)
)

# Define colors for each level
colors <- c("Unhappy" = "red", "Neutral" = "gray", "Happy" = "green")

# Plot
ggplot(data, aes(x = satisfaction, y = percent, fill = satisfaction)) +
  geom_col() +
  guides(fill = "none") + 
  scale_fill_manual(values = colors) +
  ggtitle("Your Title")  # I want this on the left of percent but going horizontal
r ggplot2
2个回答
0
投票

一种选择是使用

patchwork
将绘图标题添加为单独的
grob
:

library(ggplot2)

p <- ggplot(data, aes(x = satisfaction, y = percent, fill = satisfaction)) +
  geom_col() +
  guides(fill = "none") +
  scale_fill_manual(values = colors)

library(patchwork)

list(
  grid::textGrob("My Ttitle"),
  p
) |> 
  wrap_plots() +
  plot_layout(width = c(.1, .9))


0
投票

可能的选择:

library(ggplot2)

# Sample data
data <- data.frame(
  satisfaction = c("Unhappy", "Neutral", "Happy"),
  percent = c(20, 40, 30)
)

# Define colors for each level
colors <- c("Unhappy" = "red", "Neutral" = "gray", "Happy" = "green")

# Plot
ggplot(data, aes(x = satisfaction, y = percent, fill = satisfaction)) +
  geom_col() +
  guides(fill = "none") + 
  scale_fill_manual(values = colors) +
  coord_cartesian(xlim = c(1, NA), clip = "off") +
  annotate("text", x = -0.08, y = 20, label = "Your Title") +
  theme(plot.margin = unit(c(1,1,1,4), "lines"))

创建于 2024-04-17,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.