Reputation: 1115
I have the following dataset:
cond <- gl(15,1,labels=c("a1","a2","a3","a4","a5","b1","b2","b3","b4","b5","c1","c2","c3","c4","c5"))
pos <-c(rep("a",5),rep("b",5),rep("c",5))
mean <- c(3.202634, 3.819009, 3.287785, 4.531127, 3.093865, 3.360535, 4.084791, 3.886960, 3.297692, 4.281323, 2.418745, 3.759699, 3.553860, 4.812989, 1.606597)
hd <- c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE)
df <- data.frame(cond,pos,mean,hd)
...and generated this plot
library(ggplot2)
b <- ggplot(df, aes(x=cond, y = mean, fill=pos)) + labs(x = "X", y="Y", fill=NULL)
c <- b + geom_bar(stat = "identity", position="dodge") + theme(text = element_text(size=18), axis.text.x = element_text(colour="black", size = 14)) + scale_fill_brewer(palette="Set1")
my_theme <- theme_update(panel.grid.major = element_line(colour = "grey90"), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.ticks = element_blank(), legend.position = "none")
Now I would like to adjust the colors according to the hd
column of the dataframe such that every column of the barplot gets a slightly darker shade of the respective color (e.g. dark red instead of red) if hd=="TRUE"
.
How can I achieve that?
And an additional question: How can I increase the distance between the labs
X and Y and the plot/the axes?
Upvotes: 1
Views: 2678
Reputation: 98419
You can use function interaction()
inside aes()
to provide fill= values as combination of hd
and pos
. And then with scale_fill_manual()
provide colors.
ggplot(df, aes(x=cond, y = mean, fill=interaction(hd,pos))) +
labs(x = "X", y="Y", fill=NULL)+
geom_bar(stat = "identity", position="dodge") +
scale_fill_manual(values=c("red","darkred","blue","darkblue","green","darkgreen"))
To change position of axis title, inside function theme()
use axis.title=
for both or axis.title.x/axis.title.y
for separately x/y axis titles and then vjust=
. Values form 0 and lower will put titles lower. To ensure that there will be place for the labels you can increase plot margins with plot.margin=
(you have to add library(grid)
to use function unit).
library(grid)
your.plot + theme(plot.margin=unit(c(0.5,0.5,2,2),"cm"))+
theme(axis.title=element_text(vjust=0))
Upvotes: 7