首页 > 解决方案 > 如何使用 pivot_longer 和不同长度的向量绘制双 y 轴?

问题描述

我正在尝试使用 ggplot 绘制图表,pivot_longer但我正在努力弄清楚如何添加第二个 y 轴并绘制另一个系列。我的一些数据长度不同,所以这就是我使用的原因,pivot_longer但我不知道如何使用双 y 轴来适应它。

我不断收到的错误如下:“ Error: Aesthetics must be either length 1 or the same as the data (48): y

有什么想法可以解决这个问题吗?当我注释掉时,情节运行良好geom_line(aes(y=na))+

xstar = 0.85
x1 = c(0.87827, 0.91340, 0.92754, 0.92065, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.85643)      
x2 =  c(0.68152, 0.78534, 0.82775, 0.82965, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643, 0.85643)
x3 =  c(0.67141, 0.77874, 0.82259, 0.82487, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.77612, 0.85643)    
a = c(0.30000, 0.67141, 0.77874, 0.77874, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965, 0.82965)
b = c(0.95000, 0.95000, 0.95000, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.92754, 0.85643, 0.85643)
na = c(0, 28,  6, 57, 32, 24, 13, 92, 37, 32, 58, 17, 11, 40,  1)

acc = seq(from = 1, to = (length(a)), by = 1)

na[(length(a))] = NA
x1[(length(a))] = NA
x2[(length(a))] = NA
x3[(length(a))] = NA

totdat = tibble(acc,x1,x2,x3,b,a)
totdat
adjtotdat = pivot_longer(totdat, c(x1,x2,x3))
adjtotdat

pnas = ggplot(adjtotdat, aes(x = acc, y = value, color = name))
pnas + geom_ribbon(aes(ymin=a,ymax=b),fill= "#CCCCCC", color= "#FFFFFF", alpha=0.5)+
  geom_line(aes(y=na))+  
  geom_ribbon(aes(ymin=0,ymax=a),fill= "#333333", color= "#FFFFFF", alpha=0.5)+  
  geom_ribbon(aes(ymin=b,ymax=1),fill= "#333333", color= "#FFFFFF", alpha=0.5)+ geom_line(size=1) + geom_point(size=2) +
  geom_line(aes(y = a), color = "#336600", size = 1) + geom_point(aes(y = a), color = "#336600", size = 2)+
  geom_line(aes(y = b), color = "#006633", size= 1) +
  geom_point(aes(y = b), color = "#006633", size = 2)+
  annotate(geom = "text",x = 1+0.45, y= (min(c(a))-0.02), label = 'bold("Lower Threshold")', size = 3.5, parse = TRUE) +
  annotate(geom = "text",x = 1+0.45, y= (max(c(b)-0.02)), label = 'bold("Upper Threshold")', size= 3, parse = TRUE) +
  scale_y_continuous(breaks=seq(0,1,0.1),sec.axis = sec_axis(trans=~.*((70)), name="Number of Periods between Accidents")) +
  scale_x_continuous(breaks=seq(1,(length(a)),1)) +
  geom_hline(aes(yintercept = xstar, linetype ="Ex Ante Court Eff. Effort"), col = "green", size = 1.2)+
  scale_linetype_manual(name = "", values = c(2), guide=guide_legend(override.aes = list(color=c("green")))) +
  scale_colour_manual(values = c("blue","red","purple","#006633","#336600"), 
                      limits = c("x1","x2","x3","b","a"), name="", 
                      labels = c("Driver 1", "Driver 2", "Driver 3", "Upper Legal Threshold","Lower Legal Threshold")) 

标签: rggplot2

解决方案


推荐阅读