R语言 计算XY极坐标以将对象放置在值标签的正下方

f45qwnt8  于 2023-05-11  发布在  其他
关注(0)|答案(3)|浏览(196)

考虑以下数据集:

ig_5 <- data.frame(
  category = c("A", "B", "C", "D", "E", "F"),
  prop = c(0.1, 0.2, 0.15, 0.25, 0.05, 0.25)
) %>%
  mutate(lab.ypos = cumsum(prop) - 0.5*prop)

我用下面的代码创建了一个圆环图:

ggplot(ig_5, aes(x = 2, y = prop, fill = prop)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0) +
  geom_text(aes(y = lab.ypos, label = prop), color = "black", size = 5) +
  xlim(.5, 2.5)

如图所示,值标签位于每个类别的中间。现在,我需要在每个值标签下面放置数字rigth。我不能只将新对象粘贴到值上,因为文本和图形的颜色不同。因此,我想应该有一种方法可以使用值标签的坐标(x = 2,y= lab.ypos = cumsum(prop)- 0.5*prop)来根据我的需要定位数字。
我用geom_label添加了新图形,并给它一个与值标签的XY坐标成比例的位置。但是,我没有成功。这是我尝试过的一个例子。

ig_5 <- data.frame(
  category = c("A", "B", "C", "D", "E", "F"),
  prop = c(0.1, 0.2, 0.15, 0.25, 0.05, 0.25)) %>%
  mutate(lab.ypos = cumsum(prop) - 0.5*prop, 
         lab.ypos2 = cumsum(prop) + 0.3*prop)

 
ggplot(ig_5, aes(x = 2, y = prop, fill = prop)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0) +
  geom_text(aes(y = lab.ypos, label = prop), color = "black", size = 5) +
  geom_label(aes(y = lab.ypos,
                 x = c(1.85, 2.1, 2.2, 1.95, 1.8, 1.85),
                 label = "figure"), 
             color = 'red') +
  xlim(.5, 2.5)

我得到的结果是:

gcxthw6b

gcxthw6b1#

我有点偏见,但我认为geomtextpath在这里工作得很好:

library(geomtextpath)

ggplot(ig_5, aes(x = 2, y = prop, fill = prop)) +
  geom_bar(stat = "identity", color = "white", linewidth = 1.5) +
  coord_polar(theta = "y", start = 0) +
  geom_textpath(aes(y = lab.ypos, label = prop, group = category), 
                color = "black", size = 8, angle = 90, vjust = 1) +
  geom_labelpath(aes(y = lab.ypos, label = "figure", group = category), 
                color = "red4", size = 6, angle = 90, vjust = -1.5) +
  scale_fill_gradientn(colours = c("lightyellow", "gold", "orange")) +
  xlim(.5, 2.5) +
  theme_void(base_size = 20)

u4dcyp6a

u4dcyp6a2#

我们可以滥用vjust来垂直对齐超出正常0到1范围的标签。这将在视觉上垂直移动标签,而不考虑坐标系。工作量可能取决于输出的维度-只需尝试值,直到它工作:)

ggplot(ig_5, aes(x = 2, y = prop, fill = prop)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0) +
  geom_text(aes(y = lab.ypos, label = prop), color = "black", size = 5) +
  geom_label(aes(y = lab.ypos,
                 label = "figure"), 
             vjust = 1.5,
             color = 'red') +
  xlim(.5, 2.5)

svgewumm

svgewumm3#

另一种选择是使用ggtext::geom_richtext,通过label.margin参数可以将标签“移动”值标签大小的一半,与使用vjust = 1一起将确保标签直接放置在值标签的下方。

library(ggplot2)

ggplot(ig_5, aes(x = 2, y = prop, fill = prop)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0) +
  geom_text(aes(y = lab.ypos, label = prop),
    color = "black", size = 5
  ) +
  ggtext::geom_richtext(
    aes(
      y = lab.ypos,
      label = "figure"
    ),
    color = "red",
    label.margin = unit(2.5, "mm"),
    vjust = 1
  ) +
  xlim(.5, 2.5)

相关问题