silkita silkita - 11 months ago 65
R Question

Change direction of arrows in geom_spoke

Is there a way in

to get arrows to point to the direction of the given data? If I have data with a location (x,y) and an angle, it seems ideal to me to use
, but I would expect to be able to choose in which direction the arrows should point (away from the coordinates or pointing to them; I want the latter).

In this example, I added
to illustrate the location of my data; the radius is chosen randomly, so I want the arrow heads where the points are now (and instead of the points, of course):

df <- expand.grid(x = 1:10, y=1:10)
df$angle <- runif(100, 0, 2*pi)

ggplot(df, aes(x, y)) +
geom_point() +
coord_equal() +
geom_spoke(aes(angle = angle), radius = 0.7, arrow=arrow(length = unit(0.2,"cm")))

enter image description here

Answer Source

The arrow in geom_spoke refers to grid::arrow, which has the ends argument:

One of "last", "first", or "both", indicating which ends of the line to draw arrow heads.

Because you didn't explicitly set the ends argument, the default value of "last" was used, i.e. arrow at the end of the segment.

A small example:

p <- ggplot(df, aes(x = x, y = y, angle = angle)) +

Default value of ends:

# omitting the ends argument, like in your attempt:
p + geom_spoke(arrow = arrow(length = unit(0.2, "cm")), radius = 0.7)

# or writing out the ends argument explicitly:
p + geom_spoke(arrow = arrow(ends = "last", length = unit(0.2, "cm")), radius = 0.7)

Arrow at the start of the segment, set ends = "first":

p + geom_spoke(arrow = arrow(ends = "first"), radius = 0.7)

enter image description here