ggplot:position =“闪避”问题

时间:2010-09-22 22:04:52

标签: r ggplot2

我有一个相当简单的data.frame dput(x),下面是:

x <- structure(list(variable = c("a", "b", "c", "d", "e", "f", "g", 
"h", "i", "j", "k", "l", "m", "n", "o", "p"), top2 = c(0.51, 
0.24, 0.55, 0.36, 0.56, 0.67, 0.36, 0.22, 0.48, 0.6, 0.59, 0.06, 
0.04, 0.2, 0.26, 0.25), bottom = c(0.03, 0.05, 0.03, 0.01, 0.02, 
0.03, 0.01, 0.05, 0.03, 0, 0.03, 0.2, 0.11, 0.06, 0.16, 0.07)), .Names = c("variable", 
"top2", "bottom"), row.names = c(NA, -16L), class = "data.frame")

我想要做的是创建一个图表,显示每个“变量”彼此相邻的top2和bottom。我正在尝试实现position =“dodge”但到目前为止它似乎在很大程度上被ggplot2忽略

ggplot() + geom_bar(aes(variable, top2), data=x, position="dodge") +
geom_bar(aes(x$variable, x$bottom), data=x, position="dodge", fill="pink") + 
coord_flip()

粉红色不停留:P

1 个答案:

答案 0 :(得分:1)

这是一个快速回答

df = melt(x, id = 'variable');
names(df) = c('variable', 'topbot', 'value');
pl1 = ggplot(df, aes(x = variable, y = value)) +
      geom_bar(aes(fill = topbot, position = 'dodge')) +
      coord_flip() +
      scale_fill_manual(values = c('red', 'blue'));
print(pl1)