r - geom_label() 将标签放置在 R Shiny 中的甜甜圈图上的错误位置
问题描述
我正在尝试在我的 R Shiny 应用程序中构建一个甜甜圈图,标记与图的部分相对应的数字和百分比。但是,当我使用 geom_label() 时,它会做两件不受欢迎的事情。
- 它在图例中添加了一个“a”。
- 它将标签放置在与它们应该去的地方不对应的随机位置。
结果如下所示:
只要符合逻辑,我对标签的位置很灵活,但在理想的世界中,最终结果看起来像这样(注意:这是一个示例图,不使用下面代码中的确切数据):
当然,标签中的“a”也会被删除。
可重现的例子:
library(shiny)
library(dplyr)
library(ggplot2)
library(Cairo)
options(shiny.usecairo=T) #used to get the plot to look crisp in Shiny
my_colors <- c("#00A3AD", "#FF8200", "#753BBD", "#6CC24A")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(
fluidRow(
plotOutput("count_by_person")
))
))
server <- function(input, output) {
output$count_by_person <- renderPlot({
data <- tibble(name = c("Justin", "Corey", "Sibley", "Kate"),
n = c(10, 30, 59, 1),
prop = c(10, 30, 59, 1))
ggplot(data, aes(x = 2, y = prop, fill = name)) +
geom_bar(stat = "identity", color = "white") +
coord_polar(theta = "y", start = 0)+
geom_label(aes(label = paste0(n, "\n", prop, "%"))) +
scale_fill_manual(values = my_colors) +
theme_void() +
xlim(.5, 2.5)
})
}
shinyApp(ui, server)
用 geom_label_repel() 编辑
如下所示,我尝试使用geom_label_repel()
包中的ggrepel
而不是geom_label()
. 虽然它得到了这条线,但它并没有改变标签在错误位置的事实。
library(shiny)
library(dplyr)
library(ggplot2)
library(Cairo)
library(ggrepel)
options(shiny.usecairo=T) #used to get the plot to look crisp in Shiny
my_colors <- c("#00A3AD", "#FF8200", "#753BBD", "#6CC24A")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(
fluidRow(
plotOutput("count_by_person")
))
))
server <- function(input, output) {
output$count_by_person <- renderPlot({
data <- tibble(name = c("Justin", "Corey", "Sibley", "Kate"),
n = c(10, 30, 59, 1),
prop = c(10, 30, 59, 1)) %>%
dplyr::arrange(prop)
ggplot(data, aes(x = 2, y = prop, fill = name)) +
geom_bar(stat = "identity", color = "white") +
coord_polar(theta = "y", start = 0)+
geom_label_repel(aes(label = paste0(n, "\n", prop, "%")), force_pull = 100, nudge_x = 1) +
scale_fill_manual(values = my_colors) +
theme_void() +
xlim(.5, 2.5)
})
}
shinyApp(ui, server)
geom_label_repel() 的样子
解决方案
正如我在评论中链接的Andrey Kolyadin的非常好的回答中所解释的那样,您需要预先计算文本的累积位置:
library(ggrepel)
data %>%
arrange(desc(name)) %>%
mutate(text_y = cumsum(prop)-prop/2) %>%
ggplot(aes(x = 2, y = prop, fill = name)) +
geom_bar(stat = "identity", color = "white") +
coord_polar(theta = "y", start = 0)+
geom_label_repel(aes(y = text_y, label = paste0(n, "\n", prop, "%")), force_pull = 100, nudge_x = 1) +
scale_fill_manual(values = my_colors) +
theme_void() +
xlim(.5, 2.5)
推荐阅读
- android-studio - 带有 Windows 的 android studio 3.0 中的 Haxm 错误需要数字签名的驱动程序
- javascript - 如何在angular2中选择多个列表
- ruby-on-rails - Rails 3 更新大量数据
- java - 尽管导入类也没有得到建议,但在 Media.Type 中出现错误
- php - 如何从字符串 PHP 中分离字母、数字、取消划线和破折号
- python - 我正在使用scrapy进行刮擦。xpath 是正确的,但没有给出标签的内容
- docker - docker-compose.yml 中的 Docker 机密
- openstack - 在 RHEL 上为 Openstack Queens 安装和配置 Keystone
- selenium - 如何使用 selenium 3.12 处理 IE 11 中的通知
- docker - Dockerfile:在 RUN 指令中保留符号链接