If I understand correctly what you want, then this is largely an exercise in reshaping your data from wide to long format , so we start by doing that using pivot_longer
from tidyr 1.0.0
(you may need to upgrade).
(如果我正确理解了您想要的内容,那么这很大程度上是将数据从宽格式 pivot_longer
为长格式的练习,因此我们首先使用tidyr 1.0.0
pivot_longer
进行tidyr 1.0.0
(您可能需要升级)。)
I pivot twice since I find that easier to think about, but the pivot can probably be done in one go: (我发现了更容易思考的部分,所以我进行了两次透视,但是透视可能可以一口气完成:)
library(tidyverse)
long_data <- df1 %>%
pivot_longer(everything(),
names_to = c(".value", "set"),
names_pattern = "([A-Za-z]+)(.)") %>%
pivot_longer(-c(set, Class),
names_to = "type",
values_to = "fruit") %>%
select(set, class = Class, type, fruit)
head(long_data)
#> # A tibble: 6 x 4
#> set class type fruit
#> <chr> <fct> <chr> <fct>
#> 1 1 C M Apple
#> 2 1 C Z Orange
#> 3 2 E M Apple
#> 4 2 E Z Orange
#> 5 3 D M Apple
#> 6 3 D Z Orange
The set
variable here corresponds to the integer suffix you had in your columns before.
(这里的set
变量对应于您以前在各列中使用的整数后缀。)
Now we summarise this data: (现在我们总结一下这些数据:)
counts <- long_data %>% group_by_all %>% count
head(counts)
#> # A tibble: 6 x 5
#> # Groups: set, class, type, fruit [6]
#> set class type fruit n
#> <chr> <fct> <chr> <fct> <int>
#> 1 1 A M Apple 2
#> 2 1 A M Orange 3
#> 3 1 A Z Apple 2
#> 4 1 A Z Orange 3
#> 5 1 B M Orange 1
#> 6 1 B Z Apple 1
You could reshape this back to a wider format to get this into a matrix shape, if you wanted to, but I leave that aside here, since I gather you're interested in the plotting part, for which we need the long format anyway.
(如果愿意,您可以将其重塑为更宽的格式,以使其变为矩阵形状,但是我将其放在此处,因为我认为您对绘图部分感兴趣,因此我们仍然需要长格式。)
Hence, finally, the plot.
(因此,最后是情节。)
It's not entirely clear plot you're after, but going by the data, the following makes the most sense to me: (您所追求的情节并不完全清楚,但是根据数据来看,以下对我而言最有意义:)
ggplot(counts, aes(x = class, y = n, fill = fruit)) +
geom_histogram(position = "dodge",
stat = "identity") +
facet_wrap(~set)
#> Warning: Ignoring unknown parameters: binwidth, bins, pad
Created on 2019-12-01 by the reprex package (v0.3.0)
(由reprex软件包 (v0.3.0)创建于2019-12-01)
Play around with the aes
and facet_wrap
variables if you were after something else.
(如果您不喜欢其他方法,请facet_wrap
使用aes
和facet_wrap
变量。)