Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

r - Stacked bar chart in ggplot2

I would like plot my data in stacked bar chart. My data is like this

ID,A,B,C
D11,2,2,4
D170,2,0,6
D171,1,5,2
D1,5,0,2
D27,NA,NA,NA
D295,0,6,2

How should I start with.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
library('ggplot2')
library('reshape2')
df <- reshape2::melt(df, id.vars = 'ID')  # melt data with ID column
df <- df[!is.na(df$value), ]              # remove NA
ggplot( data = df, aes( x = ID, y = value )) +   
  geom_bar( aes( fill = variable ), stat = 'identity' )

enter image description here

Data:

df <- structure(list(ID = c("D11", "D170", "D171", "D1", "D27", "D295"),
                     A = c(2L, 2L, 1L, 5L, NA, 0L), 
                     B = c(2L, 0L, 5L, 0L, NA, 6L),
                     C = c(4L, 6L, 2L, 2L, NA, 2L)), 
                .Names = c("ID", "A", "B", "C"),
                row.names = c(NA, -6L), class = "data.frame")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...