将一列的不同值映射到图表中这些值的计数

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

我正在尝试使用

x
y
创建图表。

如何将一列的不同值映射到图表中同一列的这些值的计数。 例如,如果我有这样的数据:

column_name
1
1
2
4
1
2
2
3
3
4
2
1

我希望映射是这样的

x >> y
1 >> 4
2 >> 4
3 >> 2
4 >> 2

我尝试使用

table
函数来计算每个不同值的出现次数,它有效,但是当我将其放入
aes
函数中时,它给了我这个错误:

Aesthetics must be either length 1 or the same as the data
r ggplot2 count mapping aes
1个回答
0
投票

如果您使用

ggplot2
包,则不需要使用
table()
进行任何预处理。它获取原始数据并在内部进行计数。

比较不同值计数的简单图表是条形图。您可以将

geom_bar()
与原始数据(未计数)一起使用。但是,如果您有已统计的数据,则可以使用
geom_col()
。请参阅下面的两种方法。

使用
geom_bar()
获取未计数的数据

library(ggplot2)
df <- data.frame(column_name = c(1, 1, 2, 4, 1, 2, 2, 3, 3, 4, 2, 1))
ggplot(df, aes(x = column_name)) +
  geom_bar()

使用
geom_col()
进行预先统计的数据

counted_data <- df$column_name |>
  table() |>
  as.data.frame()

ggplot(counted_data, aes(x = Var1, y = Freq)) +
  geom_col()

这会产生与上面相同的图表。

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