首页 > 解决方案 > 在圆形条形图(ggplot2)的中心设置图例

问题描述

我正在使用本教程创建圆形条形图:https ://www.r-graph-gallery.com/295-basic-circular-barplot.html

我想在白色区域所在的条形图中间创建一个图例。但是,到目前为止,我只能在中间添加文本。如果我想用这种颜色绘制一个小立方体,它会自行缠绕,我不知道它是如何使用坐标的(我尝试了 x = 0, y = 0,结果如下,它们总是弯曲的)。

这是我添加的两行:

geom_tile(aes(x = 1, y = 0, colour = "#EB5500"), width = 100, height = 100, inherit.aes = F) +
geom_text(x = 0, aes(y = -100, label = "test"), size = 4)

所以完整的代码现在看起来像这样:

# Clear workspace 
rm(list = ls())

# Libraries
library(tidyverse)

# Create dataset
data <- data.frame(
  id=seq(1,60),
  individual=paste( "Mister ", seq(1,60), sep=""),
  value=sample( seq(10,100), 60, replace=T)
)

# Make the plot
p <- ggplot(data, aes(x=as.factor(id), y=value)) +       # Note that id is a factor. If x is numeric, there is some space between the first bar

  # This add the bars with a blue color
  geom_bar(stat="identity", fill=alpha("blue", 0.3)) +

  # Limits of the plot = very important. The negative value controls the size of the inner circle, the positive one is useful to add size over each bar
  ylim(-100,120) +

  # Custom the theme: no axis title and no cartesian grid
  theme_minimal() +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank(),
    plot.margin = unit(rep(-2,4), "cm")     # This remove unnecessary margin around plot
  ) +

  # This makes the coordinate polar instead of cartesian.
  coord_polar(start = 0) +
  geom_tile(aes(x = 1, y = 0, colour = "#EB5500"), width = 100, height = 100, inherit.aes = F) +
  geom_text(x = 0, aes(y = -100, label = "test"), size = 4)

p

但这给了我一个看起来像这样的图像:在此处输入图像描述

似乎 ggplot 会根据我添加的网格自动添加一个图例。该图例需要位于中心,并且应该是蓝色条形图而不是网格的图例。有没有办法做到这一点?

标签: rggplot2

解决方案


关于您的问题,我真正不明白的是传说中应该是什么。图例的想法是它们解释了一个映射(里面的东西aes()),所以你通常希望在你的数据中已经有了它:

library(tidyverse)

data <- data.frame(
  id=seq(1,60),
  individual=paste( "Mister ", seq(1,60), sep=""),
  value=sample( seq(10,100), 60, replace=T),
  colour = "test1" # added to have something to map to
)

现在您可以将fill美学映射到新列。要将图例移动到中心,您必须添加legend.position = c(0.5, 0.5)到您的theme.

p <- ggplot(data, aes(x=as.factor(id), y=value, fill = colour)) +       # Note that id is a factor. If x is numeric, there is some space between the first bar
  geom_bar(stat="identity") +
  ylim(-100,120) +
  theme_minimal() +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank(),
    legend.position = c(0.5, 0.5), # move legend to the center
    plot.margin = unit(rep(-2,4), "cm")     # This remove unnecessary margin around plot
  ) +
  coord_polar(start = 0)

p

我选择test1表明任何东西都可以进入数据。要更改颜色,您必须定义手动(或其他)比例:

p +
  scale_fill_manual(values = alpha("blue", 0.3))


推荐阅读