ggplot饼图,其中geom_col图按逆时针顺序绘制,违反coord_polar中的设置

9rygscc1  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(95)
library(ggplot2)
library(dplyr)

set.seed(2501)
sample_data <- data.frame(name=LETTERS[1:7], val=runif(7,0,1))

ggplot(sample_data) +
  geom_col(aes(x=1, y=val, fill=name), just = 0, width = 1) +
  geom_text(aes(x=1.5, y=val, label=name),
            position = position_stack(vjust = 0.5)) +
  xlim(c(0, 2)) +
  coord_polar(theta = "y", start = 0, direction = 1) +
  theme_void() +
  theme(axis.text = element_blank(),
        legend.title = element_blank(),
        axis.ticks = element_blank(),
        axis.line = element_blank())

在上面的R代码中,我使用geom_colcoord_polar生成了一个圆环图。通过设置direction=1coord_polar应该以顺时针顺序组织甜甜圈分数。然而,正如我们在生成的图中所看到的,彩色部分的顺序是颠倒的,而geom_text绘制的标签的顺序是正确的。我该怎么解决这个问题?

7uzetpgm

7uzetpgm1#

要以正确的顺序或与饼图切片相同的顺序放置标签,必须在geom_text中设置group美学。要获得所需的切片或堆栈顺序,您必须设置direction=-1

library(ggplot2)

set.seed(2501)
sample_data <- data.frame(name = LETTERS[1:7], val = runif(7, 0, 1))

ggplot(sample_data) +
  geom_col(aes(x = 1, y = val, fill = name), just = 0, width = 1) +
  geom_text(aes(x = 1.5, y = val, label = name, group = name),
    position = position_stack(vjust = 0.5)
  ) +
  xlim(c(0, 2)) +
  coord_polar(theta = "y", start = 0, direction = -1) +
  theme_void() +
  theme(
    axis.text = element_blank(),
    legend.title = element_blank(),
    axis.ticks = element_blank(),
    axis.line = element_blank()
  )

相关问题