2014-10-27 39 views
-1

enter image description here當x/y軸有不同的類型時,爲什麼ggplot2直方圖行爲會有所不同?

enter image description here

上頂部的直方圖是價格的濃度直方圖和在底部的直方圖是克拉的密度(菱形數據集)。

ggplot(diamonds,aes(x=price, fill=color)) + 
    geom_histogram(aes(y=..density..)) + 
    theme(legend.position="none") + 
    theme(axis.title.x=element_blank(), axis.title.y=element_blank()) 

ggplot(diamonds,aes(x=carat, fill=color)) + 
    geom_histogram(aes(y =..density..)) + 
    theme(legend.position = "none") + 
    theme(axis.title.x=element_blank(), axis.title.y=element_blank()) 

爲什麼與上述兩張圖片有所不同?怎麼做?謝謝!

+0

這實際上是一個合法的問題,不應該被關閉。看到我的答案。 – smci 2014-10-27 03:17:08

+0

我不明白哪個區別在這裏應該是相關的,是y軸上的值嗎? @stata,你可以嘗試進一步解釋,也許嘗試上傳更好版本的劇情圖片? – Marius 2014-10-27 05:00:23

+0

以png或jpeg格式導出圖表(如果您使用RStudio,很容易)應該更好地工作 – Marius 2014-10-27 05:02:12

回答

1

ggplot圖試圖根據審美(x,y,fill等)中變量的類型智能地運作。但默認不能總是正確。

在這種情況下,你的X軸有不同的類型:價格是一個整數,但克拉是數字。 如果要覆蓋默認行爲,只要使用as.numeric/as.integer/as.factor /等:

ggplot(... aes(x=as.numeric(price), ... 

隨着價格(整數),默認的統計是統計= 「BIN」。所以你得到堆疊的直方圖。

與克拉(數字),它是連續的。詳情請參閱文檔。

+0

通過使用as.numeric/as.integer/as.factor /等,我無法繪製出與上面兩張圖片相同的圖片。謝謝! – stata 2014-10-27 04:05:48

相關問題