ggplot2中的堆积条形图 [英] Stacked bar chart in ggplot2

查看:68
本文介绍了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

我应该如何开始.

推荐答案

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' )

数据:

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")

这篇关于ggplot2中的堆积条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆