我有一个data.frame xy
,我正如下面的代码所示。
我是否有办法将xy plot()中的xx
和yy
转换为points()
命令,以便我可以设置type='n'
并添加{在段命令后{1}}为了更好地控制它?
points()
如果可能的话,如果x轴可以处于固定范围(例如从1940到2014),并且如果存在1940之前的值,那么x轴应该是自动的。 y轴的范围总是不同的。我怎么能在我的代码中加入它?
答案 0 :(得分:1)
xy <- data.frame(NAME = c("NAME1", "NAME1", "NAME1", "NAME2", "NAME2", "NAME2"),
ID = c(87, 87, 87, 199, 199, 199),
X_START_YEAR = c(1984, 1986, 1984, 1899, 1909, 1924),
Y_START_VALUE = c(75, 25, -90, -8, -55, -10),
X_END_YEAR = c(1986, 1994, 1999, 1909, 1924, 1927),
Y_END_VALUE = c(20, 50, -15, -70, -80, -100))
xy
ind <- split(xy, xy$ID)
for (i in ind){
xx = unlist(i[, grep('X_', colnames(i))])
yy = unlist(i[, grep('Y_', colnames(i))])
fname <- paste0(i[1, 'ID'], '.png')
png(fname, width = 1679, height = 1165, res = 150)
# test for xx smaller than 1940
if(any(xx < 1940)) {
my_x_lim <- c(min(xx), max(xx))
} else {
my_x_lim <- c(1940, 2014)}
# plot the data using pch at your choice and color them as you like
# plot your x limits
par(mar = c(6, 8, 6, 5))
plot(xx,
yy,
main = unique(i[, 1]),
xlab = "Time [Years]",
ylab = "Value [m]",
pch = 21, col = "black",
xlim = my_x_lim)
axis(2, at = seq(-100000, 100000, 500), cex.axis = 1, labels = FALSE, tcl = -0.3)
i <- i[, -1]
segments(i[, 2], i[, 3], i[, 4], i[, 5],lwd = 2)
points(xx, yy, pch = 21, col = "black")
dev.off()
}
答案 1 :(得分:1)
ggplot2库有一个分段工具,可以将这些数据绘制得非常紧凑,因此易于维护和调整以供将来参考。在这里。
它基本上是七行,但可以进一步压缩。请注意修改x轴的额外灵感。
dat = xy
# Adapted from the other solution
if(any(dat$X_START_YEAR < 1940)) {
my_x_lim <- c(min(dat$X_START_YEAR), max(dat$X_END_YEAR))
} else {
my_x_lim <- c(1940, 2014)
}
# plot based on Hadley Wickham's ggplot2
library(ggplot2)
p = ggplot(dat)
p = p + geom_segment(aes(x = X_START_YEAR, xend = X_END_YEAR, y = Y_START_VALUE, yend = Y_END_VALUE))
# p = p + facet_wrap(~ID)
# proposal to uncomment if y-axis should not be equivalent over multiple facets (makes the plot harder to read, though):
p = p + facet_wrap(~ID, scales = "free")
# Alternatively, only let the x-axis scale vary freely (this gets you ride of the initial procedure to determine the x-axis limits)
# p = p + facet_wrap(~ID, scales = "free_x")
p = p + xlab("Time [Years]") + ylab("Value [m]")
p = p + xlim(my_x_lim)
print(p)