基于 Didzis 的回答,这是一种将 ggplot2(作者:hadley)数据转换为 geom_line 以重现 base R hist 外观的方法。
简要说明:为了让 bin 以与基础 R 相同的方式定位,我设置了 binwidth=1 和 boundary=0。为了获得类似的外观,我使用了color=black 和fill=white。为了获得相同的线段位置,我使用了ggplot_build。您会发现 Didzis 使用此技巧的其他答案。
# make a dataframe for ggplot
set.seed(1)
x = runif(100, 0, 10)
y = cumsum(x)
df <- data.frame(x = sort(x), y = y)
# make geom_histogram
p <- ggplot(data = df, aes(x = x)) +
geom_histogram(aes(y = cumsum(..count..)), binwidth = 1, boundary = 0,
color = "black", fill = "white")
# extract ggplot data
d <- ggplot_build(p)$data[[1]]
# make a data.frame for geom_line and geom_point
# add (0,0) to mimick base-R plots
df2 <- data.frame(x = c(0, d$xmax), y = c(0, d$y))
# combine plots: note that geom_line and geom_point use the new data in df2
p + geom_line(data = df2, aes(x = x, y = y),
color = "darkblue", size = 1) +
geom_point(data = df2, aes(x = x, y = y),
color = "darkred", size = 1) +
ylab("Frequency") +
scale_x_continuous(breaks = seq(0, 10, 2))
# save for posterity
ggsave("ggplot-histogram-cumulative-2.png")
可能有更简单的方法提醒您!碰巧,ggplot 对象还存储了x 的另外两个值:最小值和最大值。所以你可以用这个方便的函数制作其他多边形:
# Make polygons: takes a plot object, returns a data.frame
get_hist <- function(p, pos = 2) {
d <- ggplot_build(p)$data[[1]]
if (pos == 1) { x = d$xmin; y = d$y; }
if (pos == 2) { x = d$x; y = d$y; }
if (pos == 3) { x = c(0, d$xmax); y = c(0, d$y); }
data.frame(x = x, y = y)
}
df2 = get_hist(p, pos = 3) # play around with pos=1, pos=2, pos=3