简体   繁体   中英

Why is my faceted plot creating 2 geom_hlines with parameters passed to create only one?

I'm trying to draw one horizontal line on one panel of a facetted ggplot. If you look at the attached graphic, I want it in the bottom facet, and not the top. I'm getting it in both, and I can't recreate it. My code is below; it would be fully reproducible for any viewer if it weren't for the loading of csv data. The ggplot creation is at the end of the code, and the call to geom_hline is the 2nd line in the ggplot call. The data frame that is the source of the line parameters is jst above it, named 'mdiLevel'. I'm hoping something jumps out at someone without this being fully reproducible. Thanks in advance...

在此处输入图片说明

require("tseries")
require("zoo")
require("reshape2")
require("ggplot2")
require("grid")

filePath = "Fakepath/MDI.csv"
data = read.csv(filePath, header=TRUE, stringsAsFactors=FALSE)
data$Date = as.Date(data$Date, format="%m/%d/%y")
data = zoo(data$M.D.I., data$Date)

startDate = index(data[1])
endDate = index(data[length(data)])

spy = get.hist.quote(instrument='SPY', start=startDate, end=endDate, quote="AdjClose", 
          provider = "yahoo", origin="1970-01-01", compression = "d", retclass="zoo")

allData = merge(data, spy)
allData = na.locf(allData)
allData = allData[index(allData) %in% index(data),]

names(allData) = c('MDI', 'SPY')
allData = allData[complete.cases(allData),]
allData = data.frame(index(allData), allData)
rownames(allData) = NULL
names(allData) = c('Date', 'MDI', 'SPY')

resh = melt(allData, id='Date')

resh2 = resh
names(resh2) = c('Date', 'Var', 'Val')
resh2$Var = factor(resh2$Var, levels=c('SPY', 'MDI'))

mdiLevel = data.frame(variable='MDI', Z=0.5)

pl = ggplot(resh2, aes(x=Date, y=Val, color=Var)) + geom_line(size=1) + facet_grid(Var ~ ., scales='free') +

     geom_hline(data=mdiLevel,aes(yintercept=Z), linetype='dashed', color='darkgreen') +

     theme(legend.position='none', plot.title = element_text(vjust = 2, size=rel(1.8), 
     face="bold"), axis.text.x=element_text(color='orangered4',size=rel(1.2)), 
     axis.text.y=element_text(color='orangered4',size=rel(1.2)), axis.title.x = element_blank(), 
     axis.title.y = element_blank(), strip.text.x = element_text(size=rel(1.2)),
     panel.margin=unit(2,"lines"), strip.text.y = element_text(size=rel(1.2))) +
     ggtitle("MDI and SPY") + scale_color_brewer(palette="Set1")

plot(pl)

In the data mdiLevel you have to use the same variable names if you want the variable to be recognized as the faceting variable. Use Var instead of variable .

mdiLevel = data.frame(Var='MDI', Z=0.5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM