【问题标题】:Charts using ggplot() to apply geom_text() in R图表使用 ggplot() 在 R 中应用 geom_text()
【发布时间】:2018-02-15 04:19:28
【问题描述】:

在学习用 R 绘制图表时,我使用的是澳大利亚艾滋病生存数据。

为了显示生存中的性别,我用这些代码绘制了 2 个图表:

data <- read.csv("https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/MASS/Aids2.csv")


ggplot(data) +
  geom_bar(aes(sex, fill = as.factor(status)), position = "fill")  +
  scale_y_continuous(labels = scales::percent)

ggplot(data) +
  geom_bar(aes(as.factor(status), fill = sex))

这是图表。

现在我想将值(数字和百分比)添加到条形体中。

geom_text() 就可以了。我搜索了一些参考资料并尝试了 geom_text (x, y, label) 的不同组合,例如 xxx。它们没有正确显示。

错误代码:

geom_text(aes(as.factor(status), y = sex, label = sex))

我该怎么做?

【问题讨论】:

  • 您的“错误代码”中似乎缺少)...
  • @Dalton,谢谢。当添加“)”时,它仍然没有给我想要的。 :)
  • 试试geom_text(mapping=aes(x=as.factor(status), y=sex)) 或者只是geom_text(aes(x=as.factor(status), y=sex))...

标签: r ggplot2 charts geom-text


【解决方案1】:

我发现在ggplot 之外总结data 最容易,然后就变得相对简单了。

library(tidyverse)

data2 <- data %>%
  group_by(sex, status) %>%
  summarise (n = n()) %>%
  mutate(percent = n / sum(n) * 100)

ggplot(data2, aes(sex, percent, group = status)) +
  geom_col(aes(fill = status)) +
  geom_text(aes(label = round(percent,1)), position = position_stack(vjust = 
  0.5))

ggplot(data2, aes(status, n, group = sex)) +
  geom_col(aes(fill = sex)) +
  geom_text(aes(label = n), position = position_stack(vjust = 0.5))

【讨论】:

    猜你喜欢
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多