我有以下数据集:
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)
...并生成了这个情节
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")
现在我想根据数据框的hd
列调整颜色,使得条形图的每一列都会得到相应颜色的稍暗的阴影(例如深红色而不是红色),如果{{ 1}}。
我怎样才能做到这一点?
还有一个问题:如何增加hd=="TRUE"
X和Y与图/轴之间的距离?
答案 0 :(得分:7)
您可以使用interaction()
内的功能aes()
来提供fill =值作为hd
和pos
的组合。然后用scale_fill_manual()
提供颜色。
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"))
要更改轴标题的位置,请在内部函数theme()
内使用axis.title=
或axis.title.x/axis.title.y
分别使用x / y轴标题,然后使用vjust=
。值0和更低将使标题更低。为了确保标签的位置,您可以使用plot.margin=
增加绘图边距(您必须添加library(grid)
才能使用功能单元。)
library(grid)
your.plot + theme(plot.margin=unit(c(0.5,0.5,2,2),"cm"))+
theme(axis.title=element_text(vjust=0))