如何在R中使用ggplot2调整图例的标签位置?

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

我正在使用

ggplot2
绘制填充等高线图,并且我想调整图例标签位置。我不确定这在
ggplot2
中是否可行?

图3中的标签位置较图2上移了。图3中的标签与按键的边框对齐,图2中的标签与按键的中心对齐。此外,图 3 中的标签有“0.040”,但图 2 中没有。

library(ggplot2)
ggplot(faithfuld, aes(waiting, eruptions, z = density)) + 
  geom_contour_filled() + 
  scale_fill_brewer(name="Level")

ggplot(faithfuld, aes(waiting, eruptions, z = density)) + 
  geom_contour_filled() + 
  scale_fill_brewer(name="Level", labels = seq(0,0.04,0.005))

这是原剧情:

这就是我所取得的成就:

这就是我想要实现的目标:

r ggplot2 legend contour
1个回答
0
投票

我没有看到“这就是我所取得的成就”情节中的图例位置与原始情节有何不同。我注意到的唯一区别在于图例值的小数位数。

无论如何,上面我修改了你的代码以防它有用:

ggplot(data_df, aes(waiting, eruptions, z = density)) +
  geom_contour_filled() +
  scale_fill_brewer(name = "Level", labels = sprintf("%.3f", seq(0, 0.04, 0.005))) + 
  theme(legend.position = "bottom", 
        legend.justification = "center", 
        legend.direction = "horizontal")

sprintf 命令允许您固定小数位数。主题功能中的图例选项可让您根据需要更改标签的位置。您可以在主题功能 (?theme) 的帮助部分中查看您拥有的选项。

要仅移动图例文本,您应该编写

ggplot(data_df, aes(waiting, eruptions, z = density)) +
  geom_contour_filled() +
  scale_fill_brewer(name = "Level", labels = sprintf("%.3f", seq(0, 0.04, 0.005))) + 
  theme(legend.text = element_text(vjust = 1))

并根据需要更改文本位置。

另外,我要求 ChatGPT 创建一个数据集,该数据集可用于复制您的绘图,以防其他人想要贡献(您应该始终这样做,以便其他人更容易帮助您)。上面是它生成的代码:

# Function to generate density values for a given 'waiting' and 'eruptions' value
generate_density <- function(waiting, eruptions) {
  # Replace this with your desired density function
  # For illustration, we are using a simple example
  density_value <- dnorm(waiting, mean = 50, sd = 10) * dnorm(eruptions, mean = 3, sd = 1)
  return(density_value)
}

# Number of points along 'waiting' and 'eruptions' axes
n_points <- 100

# Generate 'waiting' and 'eruptions' values
waiting_vals <- seq(40, 100, length.out = n_points)
eruptions_vals <- seq(1, 5, length.out = n_points)

# Create an empty dataframe to store the data
data_df <- data.frame(waiting = numeric(0), eruptions = numeric(0), density = numeric(0))

# Populate the dataframe with values and their corresponding densities
for (waiting in waiting_vals) {
  for (eruptions in eruptions_vals) {
    density <- generate_density(waiting, eruptions)
    data_df <- rbind(data_df, data.frame(waiting = waiting, eruptions = eruptions, density = density))
  }
}


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