用R ggplot2中的直线和置信区间绘制主轴和副轴

时间:2019-07-18 11:13:14

标签: r ggplot2 line axis yaxis

我正在尝试用一个x轴(密度)绘制两个y轴(数字,大小)。我只想绘制数据点的均值和用均线连接的自举置信区间。这是我的代码

density <- c("1","1","1","1","1","1","1","1", "2","2","2","2","2","2","2","2","3","3","3","3","3","3","3","3","4","4","4","4","4","4","4","4")

var <- c(3,4,5,1,6,7,3,2,6,2,5,3,4,5,1,2,7,8,2,3,4,5,4,7,8,1,1,2,3,4,2,5)

z <- c("Number","Number","Number","Number","Size","Size","Size","Size","Number","Number","Number","Number","Size","Size","Size","Size","Number","Number","Number","Number","Size","Size","Size","Size","Number","Number","Number","Number","Size","Size","Size","Size")

d4 <- data.frame(density, var,z)

mycolors <- c("Number"="#F8766D", "Size" = "#F8766D")


library(ggplot2)
ggplot(d4, aes(x= density, y= var, group = z, color = z)) +
  geom_path() +
  stat_summary(fun.data=mean_cl_boot, geom="errorbar", width=0.2, colour="gray") + stat_summary(fun.y=mean, geom="point", pch=21, size=3) +
  scale_y_continuous(name="log(Number)", sec.axis = sec_axis(~ 2*., name="Size")) +
  scale_color_manual(name="z", values = mycolors)

enter image description here

我面临两个问题: a)size列占用的值比数据集中给定的值高得多。 期望的平均值是:

 Number Size
1   3.25  4.5
2   4.00  3.0
3   5.00  5.0
4   3.00  3.5

b)“数字”和“大小”的含义未正确结合在一起

还有一种方法可以为“数字”列指定带实点的实线,为“大小”列指定带三角形点的虚线

0 个答案:

没有答案