具有密集和稀疏值的R图

时间:2015-04-14 16:38:35

标签: r plot

我如何根据给定表格中的Count绘制X和Y?我不认为我可以在这里使用plot()。

X    Y    Count
-----------------
1    1       10
1    2        5
2    1       15
2    2       10

除了将所有出现的X和Y放在表格中之外,我如何从给定的表格中绘制图表?

1 个答案:

答案 0 :(得分:1)

假设X和Y是只有几个值的因子,最简单的方法是:

 data <- data.frame(X = c(1,1,2,2),
                   Y = c(1,2,1,2),
                   "Count" = c(10,5,15,10))

 data$X <- as.factor(data$X) 
 data$Y <- as.factor(data$Y)

 library(ggplot2)
 ggplot(data, aes(x = X, y = Count, fill = Y)) +
                geom_bar(stat="identity", position = position_dodge())

 data <- data.frame(X = c(1,1,2,2),
                   Y = c(1,2,1,2),
                   "Count" = c(10,5,15,10))

 data$X <- as.factor(data$X) 
 data$Y <- as.factor(data$Y)

 library(ggplot2)
 ggplot(data, aes(x = X, y = Count)) +
                geom_bar(stat="identity", position = position_dodge()) +
facet_wrap(~Y)