2

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

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

最初,这似乎很棒,因为它生成了一个包含两种分布的图形:

一张图上的两个分布

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

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

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

这将返回以下图表:

在此处输入图像描述

任何关于如何在不破坏分布的情况下更改 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

任何关于我如何添加这些线以改善图形美观的建议将不胜感激。

提前感谢您的宝贵时间。

4

1 回答 1

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)

情节1

或者,如果您更喜欢将标签保持在从线段创建的假轴附近,请包括expand = c(0, 0)x / y:

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)

情节2

于 2017-10-31T02:28:20.217 回答