1

我是 R 新手,正在使用一个数据集,该数据集涉及在调查中收集的人们最喜欢的颜色。

我只是有一个重复颜色的响应列表,所以我想制作一个我可以使用的频率表(以创建堆积条形图或饼图)。

我尝试只使用“表格”功能,但在制作绘图时我无法进一步使用创建的表格。

以下是数据示例:mostFav

1      Blue
2       Red
3       Red
4     Black
5      Blue
6     Black
7    Purple
8      Blue
9    Orange
10    White
11    Green
12    Green
13     Blue
14     Blue
15     Blue
16     Blue
17    Brown
18     Blue
19     Blue
20    Black
4

2 回答 2

1

我不确定我是否理解这个问题;这是你想要做的吗?

data <- structure(list(mostFav = c("Blue", "Red", "Red", "Black", "Blue", 
                                   "Black", "Purple", "Blue",
                                   "Orange", "White", "Green", "Green", 
                                   "Blue", "Blue", "Blue", "Blue",
                                   "Brown", "Blue", "Blue", "Black")),
                  class = "data.frame", row.names = c(NA, -20L))

# Counts for each factor
table(data)
#> data
#>  Black   Blue  Brown  Green Orange Purple    Red  White 
#>      3      9      1      2      1      1      2      1

barplot(table(data))

# Frequency
prop.table(table(data))
#> data
#>  Black   Blue  Brown  Green Orange Purple    Red  White 
#>   0.15   0.45   0.05   0.10   0.05   0.05   0.10   0.05

barplot(prop.table(table(data)))

pie(prop.table(table(data)))

reprex 包于 2022-01-25 创建(v2.0.1)

于 2022-01-25T02:51:06.647 回答
1

根据您想要做什么,您也可以尝试使用 ggplot 而不先将数据转换为表格。

mostFav <- data.frame("color" = c('Blue', 'Red', 'Red', 'Black', 'Blue', 'Black', 'Purple', 'Blue', 'Orange', 'White', 'Green', 'Green', 'Blue', 'Blue', 'Blue', 'Blue', 'Brown', 'Blue', 'Blue', 'Black'))

library(ggplot2)

ggplot(data = mostFav, aes(x = color)) +
  geom_bar()

在此处输入图像描述

于 2022-01-25T05:23:42.617 回答