【问题标题】:How to create a barplot in R with frequencies on the y-axis not the densities? [duplicate]如何在 R 中创建一个 y 轴上的频率而不是密度的条形图? [复制]
【发布时间】:2023-04-03 23:56:01
【问题描述】:

我想要以下数据的条形图。

bloodgroup <- c("O",    "A",    "A",    "O",    "O",
                "B",    "B",    "A",    "A",    "A",
                "A",    "O",    "O",    "O",    "B",
                "O",    "O",    "A",    "O",    "A",
                "A",    "O",    "AB",   "B",    "O",
                "AB",   "B",    "O",    "A",    "AB")

我编写了以下代码,但它只返回密度。我想要 y 轴上的频率,顶部每个条上的频率数。知道怎么做吗?

 barplot(prop.table(table(bloodgroup)))

【问题讨论】:

标签: r plot bar-chart


【解决方案1】:

使用ggplot2dplyr 管道尝试此方法。您需要将向量转换为数据框,然后汇总以获得计数。之后,可以使用geom_bar()geom_text() 绘制绘图以添加所需的标签。代码如下:

library(ggplot2)
library(dplyr)
#Data
bloodgroup <- c("O",    "A",    "A",    "O",    "O",
                "B",    "B",    "A",    "A",    "A",
                "A",    "O",    "O",    "O",    "B",
                "O",    "O",    "A",    "O",    "A",
                "A",    "O",    "AB",   "B",    "O",
                "AB",   "B",    "O",    "A",    "AB")
#Code
bloodgroup %>% as.data.frame %>%
  rename(Var='.') %>%
  group_by(Var) %>% summarise(N=n()) %>%
  ggplot(aes(x=Var,y=N,fill=Var))+
  geom_bar(stat = 'identity',color='black')+
  scale_y_continuous(labels = scales::comma_format(accuracy = 2))+
  geom_text(aes(label=N),vjust=-0.25,fontface='bold')+
  theme_bw()+
  theme(axis.text = element_text(color='black',face='bold'),
        axis.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'),
        legend.title = element_text(color='black',face='bold'))

输出:

或者base R:

#Code 2
xx <- barplot(table(bloodgroup),ylim=c(0, 14))
coords <- as.numeric(table(bloodgroup))
text(x = xx, y = coords, label = coords, cex = 0.8,pos = 3, col = "red")

输出:

【讨论】:

    猜你喜欢
    • 2021-03-03
    • 2015-09-13
    • 1970-01-01
    • 2022-06-11
    • 2021-05-18
    • 1970-01-01
    • 2020-05-10
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多