2017-03-31 1 views
1

plotggplot2を使用してこれらのグラフィックスが大きく異なるのはなぜですか? ggplot()コマンドを使用してhist()コマンドで作成したグラフを複製するにはどうすればよいですか?ggplotでグラフィックスを複製する

library(ggplot2) 
library(ssmrob) 
require(gridExtra) 

data(MEPS2001) 
attach(MEPS2001) 
par(mfrow=c(1,2)) 
hist(ambexp,ylim = c(0,3500),xlim=c(0,20000) ,xlab = "Ambulatory Expenses", ylab = "Freq.",main = "") 
hist(lnambx,ylim = c(0,800),xlim=c(0,12), xlab = "Log Ambulatory Expenses", ylab = "Freq.",main = "") 

enter image description here

df <- data.frame(MEPS2001) 
attach(df) 

par(mfrow=c(1,2)) 
g1 <- ggplot(data = MEPS2001, aes(ambexp)) + 
    geom_histogram(binwidth=.5, colour="black", fill="white") + 
    xlab("Ambulatory Expenses") + 
    ylab("Freq.") + 
    xlim(c(0, 20000)) + 
    ylim(c(0,3500)) 

g2 <- ggplot(data = MEPS2001, aes(lnambx)) + 
    geom_histogram(binwidth=.5, colour="black", fill="white") + 
    xlab("Log Ambulatory Expenses") + 
    ylab("Freq.") + 
    xlim(c(0, 12)) + 
    ylim(c(0,800)) 

grid.arrange(g1, g2, ncol=2) 

enter image description here

答えて

2

あなたの問題は、それらが値を中心にしているので、geom_histが自然バーを揃えていることです。 x軸を0に制限すると、0に中心を置くべきバーがカットされます(ggplotは負のx値に伸びるので表示されません)。この現象は、以下のようにgeom_histboundaryを設定することにより、望むものに変更することができます:

g1 <- ggplot(data = MEPS2001, aes(ambexp)) + 
    geom_histogram(binwidth=5000, colour="black", fill="white",boundary=0) + 
    xlab("Ambulatory Expenses") + 
    ylab("Freq.")+ 
    xlim(c(0,20000)) + 
    ylim(c(0,3500)) 

g2 <- ggplot(data = MEPS2001, aes(lnambx)) + 
    geom_histogram(binwidth=1, colour="black", fill="white",boundary=0) + 
    xlab("Log Ambulatory Expenses") + 
    ylab("Freq.") + 
    xlim(c(0, 12)) + 
    ylim(c(0,800)) 

grid.arrange(g1, g2, ncol=2) 

yelids

Histograms

+0

非常に感謝@Pdubbsが、このためにメッセージしている:警告メッセージ: 6を削除しました非有限の値を含む行 値(stat_bin)。 – fsbmat

+1

@fsbmat 'ggplot'はx軸上の上限よりも大きい行を削除します。 'table(MEPS2001 $ ambexp> 20000)'を実行すると、6つあることがわかります。私は 'hist'も同じことをすると信じている – Pdubbs

関連する問題