2017-07-17 4 views
0

Ich möchte eine Zeile zu einem Barplot hinzufügen. Wenn ich jedoch den folgenden Code verwende, passt die resultierende Zeile nicht in den Plot - sie ist zu kurz, obwohl die Datenreihe der Zeile die gleiche Länge wie die Barplot-Datenreihe hat.Zeitreihenzeile vor Barplot hinzufügen

Hier ein reproduzierbares Beispiel:

pos <- c(4,5,5,6,4,6,4,5.5,6,8,7) 
neg <- c(-8,-7,-7,-7,-6,-7,-5,-6,-6.5,-9,-7) 
net <- pos+neg 

plot.par <- par(mfrow=c(1,1)) 
par(mar=c(4,4.5,2,1)) 
plot(pos, type="n", main="", cex.main=1.1, xlab="", 
    ylab="", cex.lab=1.3, yaxt= "n", xaxt="n", ylim=c(-10, 10)) 
abline(h=c(-10,-8,-6,-4,-2,0,2,4,6,8,10),col = grey(0.6), lty=3) 
abline(v=c(1,4,7), 
     col = grey(0.6), lty=3) 
par(new=T) 
barplot(pos, main="", cex.main=1.1, xlab="", col="darkolivegreen", border="darkolivegreen", 
     ylab="", cex.lab=1.1, yaxt= "n", xaxt="n", ylim=c(-10, 10)) 
par(new=T) 
barplot(neg, main="", cex.main=1.1, xlab="", col="darkgoldenrod3",border="darkgoldenrod3", 
     ylab="", cex.lab=1.1, yaxt= "n", xaxt="n", ylim=c(-10, 10)) 
par(new=T) 
lines(net, col="firebrick4", lwd = 4) 

diesen Code verwenden, sieht das Grundstück die folgende Art und Weise: enter image description here

+0

Können Sie einige reproduzierbare Daten mit' dput hinzufügen. – Jimbou

+0

@Jimbou: Ich habe ein paar Daten hinzugefügt, hoffe, dass hilft ... – Lila

+0

@Lila können Sie die Ausgabe von 'dput (prodlong.plot)' und so weiter? – Aramis7d

Antwort

0

Sie können versuchen:

# creating the barplots 
h <- barplot(pos, ylim=c(-10,10), col="darkolivegreen", border="darkolivegreen", yaxt="n") 
barplot(neg, add=T, col="darkgoldenrod3",border="darkgoldenrod3",yaxt="n") 

# adding the horizontal ablines 
abline(h=c(-10,-8,-6,-4,-2,0,2,4,6,8,10),col = grey(0.6), lty=3) 
abline(v=h[c(1,4,7)], col = grey(0.6), lty=3) 

# plot the barplots again to overplot the ablines 
barplot(pos, ylim=c(-10,10), col="darkolivegreen", border="darkolivegreen",add=T) 
barplot(neg, add=T, col="darkgoldenrod3",border="darkgoldenrod3", yaxt="n") 

# add the line using x values stored in h...the true positions of the middle of each bar 
lines(x=h,y=net, col="firebrick4", lwd = 4) 

# the box around the plot 
box() 

enter image description here

Wie eine Alternative du kann auch ggplot2 benutzen. Die Datenaufbereitung erfolgt mit dplyr und tidyr. Alle Pakete sind in der Super-Paket tidyverse enthalten:() `zum Beispiel

library(tidyverse) 
d <- cbind.data.frame(id=seq_along(pos), pos, neg) 
d %>% mutate(net=pos+neg) %>% 
    gather(key, value, -id, -net) %>% 
    ggplot(aes(x=id, y=value, fill=key)) + 
    geom_bar(stat="identity") + 
    geom_line(aes(x=id, y=net), size=3) + 
    theme_bw() + 
    scale_x_continuous(breaks = c(1,4,7))+ 
    theme(axis.title.x=element_blank(), 
     axis.text.x=element_blank(), 
     axis.ticks.x=element_blank(), 
     panel.grid.minor.x=element_blank())+ 
    ylim(-10,10) 

enter image description here