2016-11-23 35 views
0

我希望當數值低於零時,我的酒吧是紅色的。這不是我一起工作的實際數據,但我希望這將創建一個放型能夠例如:根據數據集中的值着色geom_bars

library(ggplot2) 
library(car) 

mtcars$carnames <- rownames(mtcars) 
rownames(mtcars) <- 1:nrow(mtcars) 

subsetCars <- as.data.frame(head(mtcars, n = 20)) 
subsetCars[1,4] <- -50 

myplot.p <- ggplot(subsetCars, aes(x = subsetCars$carnames, y = subsetCars$hp)) 
myplot.p + geom_bar(stat = 'identity', 
        fill = ifelse(subsetCars$hp > 0, "lightblue", "firebrick")) + 
    coord_flip() 

link to cars barplot

一欄顯示爲紅色,而不是一個與負值。我目前也有類似的問題。 建議?

+0

它適用於我。不過,如果您指定了'data'參數,則不需要在'aes'中使用'$'子集;只需放入裸露的變量名稱即可。 – alistaire

+0

感謝您的編輯!我無法發佈圖片,所以我不得不提供鏈接。 –

回答

2

請注意,geom_bar中的fill參數採用由ifelse創建的向量,其中第一個元素是「firebrick」,其他所有元素都是「lightblue」。所以第一個(最底部的)酒吧將被填滿紅色。但是,由於觀測值按字母順序排列了carnames,所以第一個小節不對應負值的行。

甲繪製您想要的圖表的更慣用的方法是

myplot.p <- ggplot(subsetCars, aes(x = carnames, y = hp, fill = hp < 0)) 
myplot.p + geom_bar(stat = 'identity') + 
    scale_fill_manual("Negative hp", values = c("lightblue", "firebrick")) + 
    coord_flip() 

其中$子集是不必要的,因爲@alistaire指出,並且fill審美可以ggplot()加以說明。

enter image description here

+0

我想我明白了。所以Scale_fill實際上是在aes內搜索填充聲明,然後根據該參數和值內的參數更改填充? –

+0

這是正確的想法,是的。 –

0

您所遇到的問題是,當你指定填充,ggplot沒有在分配順序相同的審美,它是作爲名稱。因此,爲了確保順序得到保留,您需要將大於零的變量與其他的美學結合起來。

這種不幸的副作用是您需要手動設置顏色並移除填充比例圖例。

ggplot(subsetCars, aes(x = subsetCars$carnames, y = subsetCars$hp, 
fill = hp > 0)) + 
geom_bar(stat = 'identity') + 
coord_flip() + 
scale_fill_manual(values = c("TRUE" = "lightblue", 
"FALSE" = "firebrick")) + 
theme(legend.position = "none") 

我希望有幫助!

+0

這兩個答案的工作!謝謝。不幸的是,我的代表太低,無法投票回答。 –

相關問題