我昨天刚开始玩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))
但是当我将相同的代码应用于仅具有正值的不同数据集时,情况并非如此
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))
我发现我可以调整代码的最后一行以获得正条的蓝色, geom_bar(stat="identity",position="identity",fill="steelblue")
因此,我的两个问题是:
看起来颜色可能更接近于turquoise3而非铁蓝色。
我一定在问一个非常简单的问题。我不知道如何最好地表达它,因此很难找到解决方案。抱歉,如果您已经提出此问题,请删除我自己。
美学在这种情况下并非如此ggplot
。$colour
被视为具有两个级别的因子firebrick1
,和steelblue
,但是这些不是颜色ggplot
使用的颜色。它们只是色标的标签。ggplot
选择自己的颜色。如果要覆盖默认值,请添加以下行:
scale_fill_manual(values=c(firebrick1="firebrick1",steelblue="steelblue"))
比较一下:
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"))
这适用于所有正数(或负数)。
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"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句