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

查看:107
本文介绍了堆积的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用ggplot2和geom_bar创建一个堆积图。

以下是我的源数据:

pre> 等级F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10

我想要一个堆积图,其中x是排名,y是F1,F2,F3中的值。 p>

 #获取源数据
sample.data< - read.csv('sample.data.csv')

#图表
c< - ggplot(sample.data,aes(x = sample.data $ Rank,y = sample.data $ F1))
c + geom_bar(stat = 身份)

就我所能得到的情况而言。我不知道如何堆叠剩余字段值。

也许我的data.frame格式不正确?

解决方案

您说过:


也许我的data.frame是没有一个好的格式?


是的,这是真的。您的数据采用格式。您需要将其放在格式中。一般来说,长格式比变量比较更好。



使用 reshape2 例如,您可以使用 melt

  dat.m < -  melt(dat,id.vars =Rank)## just melt(dat )应该工作

然后你得到你的barplot:

  ggplot(dat.m,aes(x = Rank,y = value,fill = variable))+ 
geom_bar(stat ='identity')

但是使用条形图智能公式符号,您不需要重新设计数据,只需执行以下操作:

  barchart( F1 + F2 + F3〜Rank,data = dat)


I would like to create a stacked chart using ggplot2 and geom_bar.

Here is my source data:

Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10

I want a stacked chart where x is the rank and y is the values in F1, F2, F3.

# Getting Source Data
  sample.data <- read.csv('sample.data.csv')

# Plot Chart
  c <- ggplot(sample.data, aes(x = sample.data$Rank, y = sample.data$F1))
  c + geom_bar(stat = "identity")

This is as far as i can get. I'm not sure of how I can stack the rest of the field values.

Maybe my data.frame is not in a good format?

解决方案

You said :

Maybe my data.frame is not in a good format?

Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.

Using reshape2 for example , you do this using melt:

dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work

Then you get your barplot:

ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
    geom_bar(stat='identity')

But using lattice and barchart smart formula notation , you don't need to reshape your data , just do this:

barchart(F1+F2+F3~Rank,data=dat)

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

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