ggplot2 geom_line()应指向指定值 [英] ggplot2 geom_line() should point at specified value
问题描述
我写了以下代码:
library(ggplot2)
data <- structure(list(x = c(1L, 6L, 3L, 4L, 2L, 3L, 6L, 1L, 5L, 2L,
1L, 5L), y = c(1L, 7L, 5L, 6L, 3L, 4L, 6L, 2L, 5L, 6L, 5L, 2L
), year = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 2L), .Label = c("2010", "2011"), class = "factor"), matching = structure(c(1L,
2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L), .Label = c("person1",
"person2", "person3", "person4", "person5", "person6"), class = "factor")), .Names = c("x",
"y", "year", "matching"), row.names = c(NA, -12L), class = "data.frame")
data$year <- factor(data$year)
colors <- c("#4cb5ee", "#a0d099", "red")
p <- ggplot(data, aes(x=x, y=y)) +
geom_point(aes(colour=year), shape=16, size=6) +
geom_line(aes(group=matching), arrow=arrow(length=unit(0.15,"cm")), colour="black", size=1) +
xlab("x") + ylab("y") +
scale_colour_manual("year", values=colors) +
scale_x_continuous(limits=c(1,7), breaks=seq(1,7, by=1)) +
scale_y_continuous(limits=c(1,7), breaks=seq(1,7, by=1))
print(p)
它给出以下输出:
但是我想要geom_line()做的是:总是指向year = 2011的点.我无法弄清楚为什么有时箭头指向的点是是指year = 2010,有时是指向year = 2011的点.
But what I want geom_line() to do is: always points at the point where year=2011. I can't figure out why the arrow of the line is point sometimes at a point which refers to year=2010 and sometimes points at a point where year=2011.
我发现箭头包含几个参数:
What I found out is that arrow takes several arguments:
arrow(angle = 30, length = unit(0.25, "inches"), ends = "last", type = "open")
这样我可以说ends="first"
.但是我不能一概而论ends
总是first
还是总是last
.
So that I could say ends="first"
. But I can't generalize that ends
is always first
or always last
.
我试图在data.frame中添加一列,该列包含有关箭头应该是第一个还是最后一个结束的信息,但是并没有提供我想要的输出.
I tried to add a column to my data.frame which has the information if the arrow should end first or last, but it didn't gives me the output I wanted.
我们非常感谢您的帮助:-)
Every help is highly appreciated :-)
提前谢谢!
推荐答案
geom_path
应该可以解决问题:
p <- ggplot(data, aes(x=x, y=y)) +
geom_point(aes(colour=year), shape=16, size=6) +
geom_path(aes(group=matching),
arrow=arrow(length=unit(0.15,"cm")),
colour="black", size=1) +
xlab("x") + ylab("y") +
scale_colour_manual("year", values=colors) +
scale_x_continuous(limits=c(1,7), breaks=seq(1,7, by=1)) +
scale_y_continuous(limits=c(1,7), breaks=seq(1,7, by=1))
print(p)
这篇关于ggplot2 geom_line()应指向指定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!