在一个图上绘制多个密度分布

时间:2017-10-30 23:51:18

标签: r plot ggplot2 ggfortify

出于教学目的,我希望在一个图表上创建和绘制多个分布。我用来执行此操作的代码是:

library(ggplot2)
library(ggfortify)

# Create an initial graph with 1 distribution
p3 <- ggdistribution(dnorm,
                 seq(-5, 10,length=1000), 
                 colour='blue', 
                 mean=0.15,
                 sd=0.24,
                 fill='blue')

# Update p3 with second distribution
p3 <- ggdistribution(dnorm, seq(-5, 10,length=1000), 
      mean = 1.11, 
      sd = 0.55, 
      colour='green',
      fill='green',p=p3)

# View p3
p3

最初,这看起来很棒,因为它会生成包含两个分布的图形:

Two distributions on one graph

当我尝试更改图形的外观时,问题就开始了。

(1)首先,当我尝试更改y轴刻度以使其范围从0到1而不是默认显示的百分比时,我能够这样做,但是发生在发行版上。这是我正在使用的代码:

p3 <- p3 + ylim(0,1) + xlim (-2, 6) + labs(title="Plotting Multiple Distributions",  x="Mean difference", y="Density")

这将返回以下图表:

enter image description here

关于如何在不破坏分布的情况下更改y轴的任何建议都将非常感激!

(2)其次,当我尝试使用此代码沿轴添加2行时:

p3 <- p3 + geom_segment(aes(x=0, y=0, xend=0, yend=0.98),
                    size=1,       
                    arrow = arrow(length = unit(0.4,"cm")))
p3 <- p3 + geom_segment(aes(x=-2, y=0, xend=6, yend=0), 
                    size=1)

... R返回以下错误消息:

Error in eval(expr, envir, enclos) : object 'ymin' not found

关于如何添加这些线以改善图形美感的任何建议都将非常感激。

提前感谢您的时间。

1 个答案:

答案 0 :(得分:0)

听起来您希望将y轴标签更改为范围(0,1),而不会实际更改基础分布。这是一种方法:

# after obtaining p3 from the two ggdistribution() functions

# get the upper limit for p3's current y-axis range, rounded up
y.orig <- layer_scales(p3)$y$range$range[2] # = 1.662259 in my case, yours may 
                                            # differ based on the distribution
y.orig <- ceiling(y.orig * 10) / 10         # = 1.7

p3 + 
  xlim(-2, 6) +
  scale_y_continuous(breaks = seq(0, y.orig, length.out = 5),
                     labels = scales::percent(seq(0, 1, length.out = 5))) +
  annotate("segment", x = 0, y = 0, xend = 0, yend = y.orig, 
           size = 1, arrow = arrow(length = unit(0.4, "cm"))) +
  annotate("segment", x = -2, y = 0, xend = 6, yend = 0, 
           size = 1)

plot1

或者,如果您希望将标签靠近从线段创建的假轴,请为x / y包含expand = c(0, 0)

p3 + 
  scale_x_continuous(limits = c(-2, 6), expand = c(0, 0)) +
  scale_y_continuous(breaks = seq(0, y.orig, length.out = 5),
                     labels = scales::percent(seq(0, 1, length.out = 5)),
                     expand = c(0, 0)) +
  annotate("segment", x = 0, y = 0, xend = 0, yend = y.orig, 
           size = 1, arrow = arrow(length = unit(0.4, "cm"))) +
  annotate("segment", x = -2, y = 0, xend = 6, yend = 0, 
           size = 1)

plot2