在ggplot中复制图形

时间:2017-03-31 17:43:44

标签: r dataframe ggplot2

为什么这些图形使用plotggplot2变得如此不同?如何使用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

1 个答案:

答案 0 :(得分:2)

你的问题是geom_hist自然地对齐条形,因此它们以一个值为中心。通过将x轴限制为0,您可以切断应该以0为中心的条形(ggplot将不会显示它,因为它会延伸到负x值)。通过在boundary中设置geom_hist,可以将此行为更改为您想要的内容,如下所示:

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