需要帮助对数据进行分类(基于r中的2列)

问题描述 投票:1回答:2

我有2列-一列有数字(部分),另一列表明是good中的bad还是r

这里是样本数据

df <- data.frame(
  G_or_B = c("Good", "Good", "Bad", "Good", "Good", "Bad", "Good", "Good"), 
  Section = c(1,1,1,1, 2,2, 3,3) 
)

我需要一个barplot来说明每个部分,其中有多少good和多少bad。我是r的新手,但是可以很好地理解已有的代码。任何帮助表示赞赏。谢谢!

Image

r
2个回答
1
投票

使用base-r,您可以执行以下操作:

barplot(table(df), legend.text = TRUE, beside = TRUE, yaxt="n", xlab = "Section", ylab = "Freq")
axis(2, at = seq(0, 3, 1), las = 1)
# You can set beside=FALSE, if you want the bars stacked. 

输出

sample_out

数据

df <- data.frame(G_or_B = c("Good", "Good", "Bad", "Good", "Good", "Bad", "Good", "Good"), 
                 Section = c(1,1,1,1, 2,2, 3,3) )

1
投票

我希望您安装了ggplot2软件包,因为ggplot是用于创建图形的好软件包。

这是完成您想要的代码:

library(ggplot2)
df <- data.frame("G or B" = c("Good", "Good", "Bad", "Good", "Good", "Bad", "Good", "Good"), 
                 "Section" = c(1,1,1,1,2,2,3,3)  )   # This is your data frame

names(df)  # checking the variable names

ggplot(df, aes(x = Section, fill = G.or.B) )+  # Creates the bar graph with good / bad
    geom_bar() 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.