如何通过ggplot向柱状图添加另一列?

时间:2015-08-07 10:21:55

标签: r ggplot2

我有一个带有一些列的date.frame。我想在y轴上绘制所有列trt resp se,在x轴上绘制第四列class: 在这里,我成功地绘制了trt vs class的直方图。我需要的是将resp se添加到相同的直方图但颜色不同。是否可以添加标题为group的图例?

df <- data.frame( trt = c(-1, -1, 2, 2), 
resp = c(-1, 5, -3, 4), class = c("A", "B", "C", "D"), 
se = c(0.1, 0.3, 0.3, 0.2) )
ggplot(df,aes(class,trt))+
geom_bar(stat="identity",position='dodge')

2 个答案:

答案 0 :(得分:1)

或者,如果您希望每个条形图从x轴开始:

 #transform to long
library(reshape2)
df.2 <- melt(df,id.var="class")

ggplot(data=df.2) +
  geom_bar(aes(x=class,y=value,fill=variable),stat="identity",position="dodge")

产量

enter image description here

如果你想要它们堆叠也可以做,但由于负值而更加棘手。

答案 1 :(得分:0)

从命令中可以看出,您使用的是条形图而不是直方图。 希望这对你有好处:

    library(ggplot2)

    df <- data.frame( trt = c(-1, -1, 2, 2), 
                      resp = c(-1, 5, -3, 4), class = c("A", "B", "C", "D"), 
                      se = c(0.1, 0.3, 0.3, 0.2) )

 ggplot(data = df) +
  geom_bar(aes(x = class, y=trt, fill="trt"),stat="identity",position='dodge') +
  geom_bar(aes(x = class, y=resp, fill="resp"),stat="identity",position='dodge') +
  geom_bar(aes(x = class, y=se, fill="se"),stat="identity",position='dodge') +
  labs(fill = "col") + # change legend title
  ylab("VALUES") + # change y axis title
  scale_fill_manual(values=c("red","green","blue")) # pick your colors