我想将勾号和批注文本放在拼图之外,但这样做不正确.

以下是代码:

library(ggplot2)
library(ggrepel)

cars <- data.frame(category = c("civic", "MG", "Suzuki", "Tesla"),
                   count = c (14810, 6457, 18233, 571),
                   percentage = c(37,16,46,1))

ggplot(cars, aes(x="", y=count, fill=category)) +
  geom_bar(stat="identity", width=1, alpha = 0.5, color = "black") +
  coord_polar("y", start=0) +
  geom_label_repel(data = cars,
                   aes(y = count, label = paste0(percentage, "%")),
                   size = 4.5, nudge_x = 1, show.legend = FALSE) +
  labs(fill = "Category") +
  scale_color_gradientn(colours = rainbow(4)) +
  theme_void() +
  theme(legend.position = "right",
        text = element_text(family = "serif", colour = "black"))

enter image description here

但我想要的是:

enter image description here

推荐答案

为了获得您想要的结果,您必须使用x = 1.5将标签放置在边界上,其中1是x轴类别""的"数字"位置,而.5占条带宽度的(一半).

此外,要对齐标签和馅饼的切片,如果要使用nudge_x,则必须手动计算位置.原因是,与geom_bar相比,geom_text(_repel)在默认情况下不会使用position="stack",但因为您已经使用position_nudge(通过nudge_x),所以不能使用position_stack来堆叠标签.

library(ggplot2)
library(ggrepel)
library(forcats)
library(dplyr, warn=FALSE)

cars <- data.frame(
  category = c("civic", "MG", "Suzuki", "Tesla"),
  count = c(14810, 6457, 18233, 571),
  percentage = c(37, 16, 46, 1)
)

cars <- cars |>
  mutate(category = forcats::fct_inorder(category)) |> 
  arrange(desc(category)) |> 
  mutate(
    pos = cumsum(count),
    pos = .5 * (pos + lag(pos, default = 0))
  )

ggplot(cars, aes(x = "", y = count, fill = category)) +
  geom_bar(stat = "identity", width = 1, alpha = 0.5, color = "black") +
  geom_label_repel(
    aes(x = 1.5, y = pos, label = paste0(percentage, "%")),
    size = 4.5, nudge_x = .5, show.legend = FALSE,
  ) +
  labs(fill = "Category") +
  scale_color_gradientn(colours = rainbow(4)) +
  theme_void() +
  theme(
    legend.position = "right",
    text = element_text(family = "serif", colour = "black")
  ) +
  coord_polar("y", start = 0)

R相关问答推荐

是否有任何解决方案可以优化VSCode中RScript的图形绘制?

变量计算按R中的行更改

如何在R中正确对齐放射状图中的文本

编码变量a、b、c以匹配来自另一个数据点的变量x

在垂直轴中包含多个ggplot2图中的平均值

pickerInput用于显示一条或多条geom_hline,这些线在图中具有不同 colored颜色

任意列的欧几里得距离

计算具有奇数日期的运行金额

R根据条件进行累积更改

如何优化向量的以下条件赋值?

当我添加美学时,geom_point未对齐

如何对r中包含特定(未知)文本的行求和?

有没有办法一次粘贴所有列

使用ifElse语句在ggploy中设置aes y值

在r中整理图例和堆叠图的问题

如何判断代码是否在R Markdown(RMD)上下文中交互运行?

长/纬点继续在堪萨斯-SF结束,整齐的人口普查

使用&Fill&Quot;在gglot中创建 colored颜色 渐变

动态统计函数在ShinyApp内部更改

在分面的ggplot2条形图中对条形图进行排序,并省略每组未使用的系数级别