我有一个示例data.frame xy
,我正在使用以下代码进行绘制:
xy <- structure(list(NAME = structure(c(3L, 3L, 3L, 1L, 1L, 1L, 4L, 4L, 2L, 2L, 2L), .Label = c("EXAMPLE2", "EXAMPLE5", "TEST1", "TEST3"), class = "factor"), ID = c(6L, 6L, 6L, 3367L, 3367L,3367L, 3367L, 3367L, 3366L, 3366L, 3366L), X_START_YEAR = c(1999L, 2000L, 2001L, 2001L, 2002L, 2003L, 2005L, 2006L, 2001L, 2002L,2003L), Y_START_VALUE = c(0L, -570L, -630L, 0L, -140L, -660L,-770L, -1630L, 0L, 20L, -140L), X_END_YEAR = c(2000L, 2001L, 2002L, 2002L, 2003L, 2004L, 2006L, 2007L, 2002L, 2003L, 2004L), Y_END_VALUE = c(-570L, -630L, -1190L, -140L, -660L, -650L, -1630L, -2170L, 20L, -140L, -60L), TITLE_LEGEND = structure(c(3L, 3L, 3L, 1L, 1L, 1L, 4L, 4L, 2L, 2L, 2L), .Label = c("Example 2", "Example 5", "Test 1", "Test 3"), class = "factor"), FILENAME = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "PLOTTEST", class = "factor"), TITLE_PLOT = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,1L, 1L, 1L), .Label = "PLOT TEST", class = "factor"), X_AXIS_START = c(1940L,1940L, 1940L, 1940L, 1940L, 1940L, 1940L, 1940L, 1940L, 1940L,1940L), X_AXIS_END = c(2014L, 2014L, 2014L, 2014L, 2014L,2014L, 2014L, 2014L, 2014L, 2014L, 2014L)), .Names = c("NAME", "ID", "X_START_YEAR", "Y_START_VALUE", "X_END_YEAR", "Y_END_VALUE","TITLE_LEGEND", "FILENAME", "TITLE_PLOT", "X_AXIS_START", "X_AXIS_END"), class = "data.frame", row.names = c(NA, -11L))
xy2 <- xy
tt <- as.integer(xy2$TITLE_LEGEND) # define legend parameters
title <- unique(xy[,9])
filename <- xy$FILENAME
my_x_lim <- c(xy$X_AXIS_START, xy$X_AXIS_END)
fname <- paste0(filename, '.png')
png(fname, width=1679, height=1165, res=150)
par(mar=c(6,8,6,5))
plot(c(xy[,3],xy[,5]),c(xy[,4],xy[,6]),type="n",main=title,xlab="Time [Years]", ylab="VALUE [mm]", cex.main=1.5,cex=1, xlim = unique(my_x_lim), font.lab=2, cex.lab=1.3, cex.axis=1.2)
axis(1, at = seq(1000, 2050, 5), cex.axis=1, labels=FALSE, tcl=-0.3)
axis(2, at = seq(-100000, 100000, 500), cex.axis=1, labels=FALSE, tcl=-0.3)
abline(h=0, col = "gray60")
segments(xy[,3], xy[,4], xy[,5], xy[,6], lty=tt)
#insert legend based on options defined before
tt <- unique(tt)
legend("bottomleft",lty=tt,legend=levels(xy2$TITLE_LEGEND)[tt],bty='n')
dev.off()
这一切都很好,但我不确定如何在图例中定义不同的线型样式。
我的问题:我如何定义始终定义线型样式顺序的不同线型样式(例如,对于第一个图例项,始终放置粗线,对于第二个项目,虚线和第三项虚线等)?
正如我在我的例子中所理解的那样,目前尚未明确定义。例如,如果我使用其他数据绘图并再次使用此绘图代码,则线型样式的顺序是完全不同的顺序,有时在图例中将相同的样式绘制两次。
答案 0 :(得分:1)
这是因为您的TITLE_LEGEND列是一个因素,所以当您执行as.integer(xy2$TITLE_LEGEND)
时,第一级获得1,第二级获得2,依此类推。
如果您想先进行“测试1”,然后再进行“示例2”等,则需要对因子进行重新排序。
xy2$TITLE_LEGEND<-factor(xy2$TITLE_LEGEND,levels=c("Test 1","Example 2","Test 3","Example 5"))
然后as.integer(xy2$TITLE_LEGEND)
应该工作,“示例5”由lty = 4表示。