简体   繁体   中英

How to draw bar plot using frequency table in ggplot2

data.frame format:

a <- data.frame(c(1,2,3),c(3,2,1))
colnames(a) <- c("A","B","C")
rownames(a) <- c("X","Y")

  A B C
X 1 2 3
Y 3 2 1

How to use this kind of frequency table to draw barplot in ggplot2?

I guess this table need to be somehow melted in a particular way to be compatible with the barplot function in ggplot2.

 Var1 Var2    
  X   A
  X   B
  X   B
  X   C
  X   C   
  X   C
  Y   A
  Y   A
  Y   A
  Y   B
  Y   B
  Y   C

The final plot would be similar like this: 在此处输入图像描述

In tidyverse , you can use gather() function.

library(ggplot2)
library(tidyr)

a <- tibble(x = c(1,2,3), y = c(3,2,4), group = letters[1:3])
a <- gather(a, key = "key", value = "value", -group)
print(a)
# A tibble: 6 x 3
  group key   value
  <chr> <chr> <dbl>
1 a     x         1
2 b     x         2
3 c     x         3
4 a     y         3
5 b     y         2
6 c     y         4
ggplot(a, aes(key, value, fill = group)) +
  geom_col()

Will produce this plot: 柱状图

Starting with your table:

M = as.table(matrix(c(1,3,2,2,3,1),ncol=3))
rownames(M) = c("X","Y")
  A B C
X 1 2 3
Y 3 2 1
class(M)
[1] "table"

We need to pivot it long like you said, but it is done once you convert a table into a data.frame:

as.data.frame(M)

  Var1 Var2 Freq
1    X    A    1
2    Y    A    3
3    X    B    2
4    Y    B    2
5    X    C    3
6    Y    C    1

So we plot:

library(ggplot2)
library(ggthemes)

ggplot(as.data.frame(M),aes(x=Var1,y=Freq,fill=Var2)) + 
geom_col(width=0.3) + theme_excel_new() + scale_fill_excel_new()

在此处输入图像描述

If you already have a data.frame:

M = as.data.frame.matrix(M)
class(M)
[1] "data.frame"

library(tidyr)
library(dplyr)

M %>% rownames_to_column("Var1") %>% 
pivot_longer(-Var1,names_to ="Var2",values_to="Freq") %>
ggplot(as.data.frame(M),aes(x=Var1,y=Freq,fill=Var2)) + 
geom_col(width=0.3) + theme_excel_new() + scale_fill_excel_new()

This will work

a <- data.frame(c(1,3),c(2,2), c(3,1))
colnames(a) <- c("A","B","C")
rownames(a) <- c("X","Y")

library(data.table)
library('ggplot2')

a$row<- rownames(a)
am<-melt(a, id.vara=row)
ggplot(am, aes(fill=variable, y=value, x=row)) + 
  geom_bar(position="stack", stat="identity")

Barplot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM