r - 在圆形条形图(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 会根据我添加的网格自动添加一个图例。该图例需要位于中心,并且应该是蓝色条形图而不是网格的图例。有没有办法做到这一点?
解决方案
关于您的问题,我真正不明白的是传说中应该是什么。图例的想法是它们解释了一个映射(里面的东西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))
推荐阅读
- html - 以子对象为目标时触发父对象的转换
- java - 如何忽略 2 个具有相同 ID 的用户并只打印第一个用户?
- teradata - 从“客户端 tdp 会话号”到“会话号”
- ruby-on-rails - Ruby On Rails - 用于保存 CRUD 操作参数/有效负载的数据库结构
- python - 这个带有 sha256 和 PBKDF2HMAC + salt 的密码功能是否可以安全地在 python 中加密您的本地密码?
- excel - 用于识别 Excel 单元格格式模式的 UDF(用户定义函数)
- google-cloud-platform - 谷歌云个人计费账户
- python - Mujoco 安装,找不到二进制文件
- yaml - GitLab CI yml 检查值是否在工作流规则的数组内
- typescript - 数组数组的打字稿递归类型