使用此数据框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
我想绘制一个条形图,其中x轴为分组,y轴为金钱。此外,我希望条形图由它们发生的条件分开/分解。到目前为止,我使用了以下代码,它几乎是理想的。我有分组考虑的条形图,我只想按条件进一步考虑它。
qplot(factor(bat.group), data = df, geom = "bar", fill = bat.group,
weight = bat.money, position = "dodge")
这会产生这里看到的图像。
答案 0 :(得分:1)
您通常可以使用interaction
函数进行分组:
qplot(interaction(bat.condition, bat.group), data = df, geom = "bar", fill = bat.group,
weight = bat.money, position = "dodge")
答案 1 :(得分: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)
答案 2 :(得分:0)
这是一个我认为你要求的解决方案。我使用ggplot
语法而不是qplot
。我使用facet_wrap
通过bat.condition分隔您的数据。此外,geom_barplot
需要参数stat="identity"
,否则它会尝试将您的数据存储起来。
# 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)
修改强>
使用fill=bat.condition
并添加position="dodge"
会产生一个与您在评论中链接的图形一样的数字。
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)