ggplot“前卫”分布图

时间:2015-09-23 08:05:43

标签: r plot ggplot2

我使用ggplot2使用以下代码绘制具有两个密度的直方图:

ggplot(khstat_wide, aes(x=khstat_vorher)) + geom_histogram(aes(y=..density..),binwidth=200) +
ylim(0,0.004) + xlim(0,10000) + scale_colour_brewer(palette="Dark2") +
stat_function(fun = dtweedie, aes(colour = 'Tweedie'), args = list(xi=round(out3$p.max,4), mu=mean(khstat_wide$khstat_vorher),phi=out3$phi.max)) +
theme(title=element_text(size=14),axis.text=element_text(size=12), legend.text=element_text(size=12),
    legend.position=c(.85,.85), legend.title=element_blank()) +
stat_function(fun = dgamma, aes(colour = 'Gamma' ), args = list(shape=1.199157e-01, scale=1.138242e+04 )) 

enter image description here

请注意,我设置了ylim(0,0.004) + xlim(0,10000)但这样做会更改直方图的比例,因为省略了超出此范围的值。

这是与coord_cartesian(ylim=c(0,0.004),xlim=c(0,5000))相同的情节,但现在密度线看起来真实“前卫”:

enter image description here

我怎样才能让它们再次光滑?

更新:

很难建立一个可重复的例子,这是一个尝试:

a <- rgamma(500, shape=0.5)
b <- rep(0,300)
df <- data.frame(V1=c(a,b), V2=0)

工作的:

ggplot(df, aes(x=V1)) + geom_histogram(aes(y=..density..),binwidth=200) +
 ylim(0,0.01) + xlim(0,1000) + scale_colour_brewer(palette="Dark2") +
stat_function(fun = dgamma, aes(colour = 'Gamma' ), args =   list(shape=1.199157e-01, scale=1.138242e+04 )) 

不起作用:

ggplot(df, aes(x=V1)) +  geom_histogram(aes(y=..density..),binwidth=200) +
scale_colour_brewer(palette="Dark2") +
stat_function(fun = dgamma, aes(colour = 'Gamma' ), args =  list(shape=1.199157e-01, scale=1.138242e+04 )) +
coord_cartesian(ylim=c(0,0.01),xlim=c(0,1000))

1 个答案:

答案 0 :(得分:0)

这解决了我的问题。

首先,创建原始图表的对象

p <- ggplot(df, aes(x=V1)) + geom_histogram(aes(y=..density..),binwidth=200) +
  scale_colour_brewer(palette="Dark2") +
  stat_function(fun = dgamma, aes(colour = 'Gamma' ), args =   list(shape=1.199157e-01, scale=1.138242e+04 )) +
  ylim(0,0.01) + xlim(0,1000)

现在将coord_cartesian()与您想要的限制一起使用

p + coord_cartesian(ylim=c(0,0.01),xlim=c(0,500))

enter image description here

相关问题