[英]How to plot a data frame with multiple frequencies for a factor?
I have this data frame: 我有这个数据框:
df <- data.frame(make = c("dodge", "dodge", "toyota", "ford", "dodge", "toyota","toyota","ford", "ford", "dodge"),
grn = c( 1, 1, NA, 1, NA, NA, 1, 1, NA, NA),
blu = c( NA, NA, 1, NA, 1, NA, NA, NA, 1, NA),
blk = c( NA, NA, NA, NA, NA, 1, NA, NA, NA, 1))
I am trying to create a plot with "make" on the x-axis and the total "make" count for the y-axis and fill using the colors. 我正在尝试在x轴上创建带有“ make”的图,在y轴上创建总“ make”数,并使用颜色填充。 I think I need to make a count table for the make and color but am unsure how to do this.
我认为我需要为颜色和颜色制作一张计数表,但不确定如何执行此操作。 For example the table would look something like this:
例如,该表将如下所示:
DF <- read.table(text = "make grn blu blk
dodge 2 1 1
ford 2 1 0
toyota 1 1 1", header = TRUE)
Then the solution is pretty straight forward 然后解决方案很简单
library(reshape2)
library(ggplot2)
DF1 <- melt(DF, id.var="make")
ggplot(DF1, aes(x = make, y = value, fill = variable)) +
geom_bar(stat = "identity")
So how can I transform my data frame "df" into "DF"? 那么如何将数据框“ df”转换为“ DF”?
Well you don't have to make all these transformation. 好吧,您不必进行所有这些转换。 The shorter way of making plot:
绘制情节的较短方法:
df %>%
gather(key=col, value=num, -make) %>%
na.omit() %>%
ggplot(aes(make, fill=col)) +
geom_bar()
First three rows create the long form of the input data. 前三行创建输入数据的长格式。 Then it is passed to
ggplot
to make the statistical transformations for you. 然后将其传递给
ggplot
为您进行统计转换。
You can use dplyr::summarise_all
: 您可以使用
dplyr::summarise_all
:
library(dplyr)
df %>% group_by(make) %>% summarise_all(sum, na.rm=TRUE)
# A tibble: 3 × 4
# make grn blu blk
# <fctr> <dbl> <dbl> <dbl>
#1 dodge 2 1 1
#2 ford 2 1 0
#3 toyota 1 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.