【发布时间】:2012-01-16 17:46:29
【问题描述】:
我正在尝试在 ggplot 调用中自动设置线型,我将 在 for 循环中运行。数据在 var2 变量中有大约 20 个值,我循环取 Eurostoxx(指数)和一个其他值一次绘制。
这是第一行:
Date value var1 var2
2011-09-30 20.67 Return on Equity Eurostoxx
我想在每张图表中将 Eurostoxx 设为实线(这令人困惑 切换时向读者展示)。
我知道如何手动设置线型:
gp<- gp + scale_linetype_manual("",values=c("Eurostoxx"="dotted","Automobiles and Parts"="solid"))
但我尝试将其自动化
secnam<-unique(g$var2)[!unique(g$var2)%in%"Eurostoxx"]
secnam
#"Automobiles and Parts"
gp<- gp + scale_linetype_manual("",values=c("Eurostoxx"="dotted",secnam="solid"))
遇到错误
data.frame(scale$output_breaks(), I(scale$labels())) 中的错误: 行名包含缺失值
下面的代码重现了这个问题。
gfull<-structure(list(Date = structure(c(15247, 15278, 15308, 15338,
15247, 15278, 15308, 15338, 15247, 15278, 15308, 15338, 15247,
15278, 15308, 15338, 15247, 15278, 15308, 15338, 15247, 15278,
15308, 15338), class = "Date"), value = c(20.67, 19.81, 19.81,
19.92, 1.2966, 1.4054, 1.3744, 1.3828, 16.36, 16.58, 16.86, 16.7,
0.8263, 0.9167, 0.8642, 0.8197, 13.32, 12.82, 12.59, 12.55, 1.1672,
1.1721, 1.1643, 1.1509), var1 = c("Return on Equity", "Return on Equity",
"Return on Equity", "Return on Equity", "Price to Book", "Price to Book",
"Price to Book", "Price to Book", "Return on Equity", "Return on Equity",
"Return on Equity", "Return on Equity", "Price to Book", "Price to Book",
"Price to Book", "Price to Book", "Return on Equity", "Return on Equity",
"Return on Equity", "Return on Equity", "Price to Book", "Price to Book",
"Price to Book", "Price to Book"), var2 = c("Eurostoxx", "Eurostoxx",
"Eurostoxx", "Eurostoxx", "Eurostoxx", "Eurostoxx", "Eurostoxx",
"Eurostoxx", "Automobiles and Parts", "Automobiles and Parts",
"Automobiles and Parts", "Automobiles and Parts", "Automobiles and Parts",
"Automobiles and Parts", "Automobiles and Parts", "Automobiles and Parts",
"Utilities", "Utilities", "Utilities", "Utilities", "Utilities",
"Utilities", "Utilities", "Utilities")), .Names = c("Date", "value",
"var1", "var2"), row.names = c(71L, 72L, 73L, 74L, 4511L, 4512L,
4513L, 4514L, 145L, 146L, 147L, 148L, 4585L, 4586L, 4587L, 4588L,
1477L, 1478L, 1479L, 1480L, 5917L, 5918L, 5919L, 5920L), class = "data.frame")
代码:
g<-gfull
g<-subset(gfull, var2 %in% c("Eurostoxx","Automobiles and Parts") )
gp <- ggplot(g, aes(Date, value,group=var2,lty=var2))
gp <-gp + facet_grid(var1~., scales="free")
gp<- gp + geom_line()
#EUROSTOXX is dotted
g<-gfull
g<-subset(g,var2%in%c("Eurostoxx","Utilities"))
gp <- ggplot(g, aes(Date, value,group=var2,lty=var2))
gp <-gp + facet_grid(var1~., scales="free")
gp<- gp + geom_line()
#EUROSTOXX is solid
secnam<-unique(g$var2)[!unique(g$var2)%in%"Eurostoxx"]
gp<- gp + scale_linetype_manual("",values=c("Eurostoxx"="dotted",secnam="solid"))
gp
#Error in data.frame(scale$output_breaks(), I(scale$labels())) :
#row names contain missing values
【问题讨论】:
-
你能用代码块格式化你的代码吗?
-
您可以在
data.frame中创建一个包含所需线型值的新变量,然后使用scale_linetype_identity(未经测试)。 -
感谢 cmets 伙计们。下次我会查找这个代码块功能。 Baptiste,您的建议是正确的,正如 Joran 在下面所详述的那样。