我昨天刚开始玩ggplot.具有负值的条形图的代码按我的预期工作:
dtf1 <- data.frame(ID = c(1:10),Diff = c(-5:4))
dtf1$colour <- ifelse(dtf1$Diff < 0, "firebrick1","steelblue")
dtf1$hjust <- ifelse(dtf1$Diff > 0, 1.3, -0.3)
ggplot(dtf1,aes(ID,Diff,label="",hjust=hjust))+
geom_text(aes(y=0,colour=colour))+
geom_bar(stat="identity",position="identity",aes(fill = colour))
Run Code Online (Sandbox Code Playgroud)
但是,当我将相同的代码应用于仅具有正值的其他数据集时,情况并非如此
dtf <- data.frame(ID = c(1:10),Diff = rnorm(10,3))
dtf$colour <- ifelse(dtf$Diff < 0, "firebrick1","steelblue")
dtf$hjust <- ifelse(dtf$Diff > 0, 1.3, -0.3)
ggplot(dtf,aes(ID,Diff,label="",hjust=hjust))+
geom_text(aes(y=0,colour=colour))+
geom_bar(stat="identity",position="identity",aes(fill = colour))
Run Code Online (Sandbox Code Playgroud)

我发现我可以调整代码的最后一行,为我的正条形图获得蓝色,
geom_bar(stat="identity",position="identity",fill="steelblue")
因此,我的两个问题是:

看起来颜色可能更接近绿松石3而不是钢蓝.
我一定是在问一个非常简单的问题.我不知道如何最好地表达它,因此很难找到解决方案.如果问题已被提出,我很抱歉,我很乐意删除自己.
美学在这方面不起作用ggplot.$colour被视为具有两个级别的因子firebrick1,和steelblue,但这些不是颜色ggplot用途.它们只是色标的标签.ggplot选择它自己的颜色.如果要覆盖默认值,请添加以下行:
scale_fill_manual(values=c(firebrick1="firebrick1",steelblue="steelblue"))
Run Code Online (Sandbox Code Playgroud)
与此相比:
dtf1$colour <- ifelse(dtf1$Diff < 0, "negative","positive")
ggplot(dtf1,aes(ID,Diff,label="",hjust=hjust))+
geom_bar(stat="identity",position="identity",aes(fill = colour))+
scale_fill_manual(values=c(positive="firebrick1",negative="steelblue"))
Run Code Online (Sandbox Code Playgroud)

这适用于所有积极(或消极).
dtf <- data.frame(ID = c(1:10),Diff = rnorm(10,3))
dtf$colour <- ifelse(dtf$Diff < 0,"negative","positive")
dtf$hjust <- ifelse(dtf$Diff > 0, 1.3, -0.3)
ggplot(dtf,aes(ID,Diff,label="",hjust=hjust))+
geom_bar(stat="identity",position="identity",aes(fill = colour))+
scale_fill_manual(values=c(positive="firebrick1",negative="steelblue"))
Run Code Online (Sandbox Code Playgroud)
