3

Using this dataframe, df:

bat.condition bat.group      bat.money
1              safe          2825.882
2              safe          2931.875
1              glsa          6975.882
2              glsa          5407.500
1              studyabroad   3084.706
2              studyabroad   2253.750 
1              jcc           4134.706
2              jcc           5550.625
1              eagg          4578.824
2              eagg          5456.250

I would like to plot a bar chart with group on the x axis, money on the y axis. Further, I would like the bars to be separated/factored by the condition in which they occur. So far I have used the following code and it is nearly ideal. I have the bars factored by group, I would just like to further factor it by condition.

qplot(factor(bat.group), data = df, geom = "bar", fill = bat.group, 
      weight = bat.money, position = "dodge")

Which produces the image seen here.

enter image description here

4

3 に答える 3

1

データフレームに新しい変数を追加して、次のようなファセットを使用できます。

df$factor = factor(df$bat.group)
qplot(as.character(bat.condition), data = df, geom = "bar", fill = bat.group, 
      weight = bat.money, position = "dodge", facets = . ~ factor)

結果

于 2012-11-07T23:29:02.007 に答える
1

通常、次のinteraction関数を使用してグループ化を取得できます。

 qplot(interaction(bat.condition, bat.group), data = df, geom = "bar", fill = bat.group, 
      weight = bat.money, position = "dodge")
于 2012-11-07T23:09:33.163 に答える
0

Here is a solution that does what I think you are asking for. I have used ggplot syntax instead of qplot. I have used facet_wrap to separate your data by bat.condition. Also, geom_barplot needs the parameter stat="identity" or else it will try to bin your data.

# Using ggplot2 version 0.9.2.1
library(ggplot2)

dat = read.table(header=TRUE, 
text="bat.condition bat.group      bat.money
1              safe          2825.882
2              safe          2931.875
1              glsa          6975.882
2              glsa          5407.500
1              studyabroad   3084.706
2              studyabroad   2253.750 
1              jcc           4134.706
2              jcc           5550.625
1              eagg          4578.824
2              eagg          5456.250")


p1 = ggplot(data=dat, aes(x=bat.group, y=bat.money, fill=bat.group)) +
     geom_bar(stat="identity") +
     facet_wrap(~ bat.condition)

ggsave(plot=p1, filename="plot_1.png", height=5, width=8)

enter image description here

Edit: Using fill=bat.condition and adding position="dodge" will produce a figure like the one you have linked to in your comment.

p2 = ggplot(data=dat, aes(x=bat.group, y=bat.money, fill=factor(bat.condition)))+
     geom_bar(position="dodge")

ggsave(plot=p2, filename="plot_2.png", height=4, width=6)

enter image description here

于 2012-11-07T23:06:43.873 に答える