2017-03-31 59 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_hist如下設置boundary改爲你想要什麼:

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軸上限的行。運行'表(MEPS2001 $ ambexp> 20000)',你會看到有六個。我相信'hist'也是一樣的 – Pdubbs