【问题标题】:Replicating graphics in ggplot在ggplot中复制图形
【发布时间】:2017-03-31 17:43:43
【问题描述】:

为什么这些图形使用plotggplot2 会变得如此不同?如何使用ggplot() 命令复制使用hist() 命令制作的图形?

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 = "")

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)

【问题讨论】:

    标签: r dataframe ggplot2


    【解决方案1】:

    您的问题是 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)
    

    yield

    【讨论】:

    • 非常感谢@Pdubbs,但是因为有这个消息:警告消息:删除了 6 行包含非有限值(stat_bin)。
    • @fsbmat 即ggplot 删除大于 x 轴上限的行。运行table(MEPS2001$ambexp&gt;20000),你会看到有六个。我相信hist 会做同样的事情
    猜你喜欢
    • 1970-01-01
    • 2018-11-18
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多