Reputation: 1029
I have a date.frame with some columns.I want to plot all columns trt resp se
on y axis and the forth column class
on x axis:
here i succeeded to plot a histogram of trt vs class
. What I need is just add resp se
to the same histogram but with different colours.Is it possible to add a legend with a title 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')
Upvotes: 0
Views: 766
Reputation: 13139
Or, if you wanted each bar to start on the x-axis:
#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")
yields
If you want them stacked that can be done too, but is more tricky due to the negative values.
Upvotes: 1
Reputation: 16121
As you can see from your commands you are using a bar plot not a histogram. Hope this is good for you:
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
Upvotes: 0