How do you label a horizontal line when the x axis is categorical?
There is a worked example that shows how to label a straight line in R using ggplot2. Please look at example 5 - "Recreate the following plot of flight volume by longitude".
How do you code if the x axis was ca开发者_如何学运维tegorical instead of continuous? How would one write the part of the syntax in geom_text that is currently
data = data.frame(x = - 119, y = 0)
I created a line
+ geom_text(aes(x,y, label = "seronegative"),
data = data.frame(x = 1, y = 20),
size = 4, hjust = 0, vjust = 0, angle = 0)
and I tried several options
data = data.frame(x = 1, y = 20)
data = data.frame(x = factor(1), y = 20)
#where gard is the name of one of the categories
data = data.frame(x = "gard", y = 20)
...but I get the error
invalid argument to unary operator
It's not entirely clear to me what you're trying to do, since you say you try to create a line, and then your code uses geom_text
. Assuming that you'd like to place a vertical line, with a text label oriented vertically on that line, using a categorical x variable, here's a simple example:
dat <- data.frame(x = letters[1:5],y = 1:5)
txt <- data.frame(x = 1.5, y = 1, lab = "label")
ggplot(dat,aes(x = x, y = y)) +
geom_point() +
geom_vline(xintercept = 1.5) +
geom_text(data = txt,aes(label = lab),angle = 90, hjust = 0, vjust = 0)
which on my machine produces this output:
Note that I put the text labels in a separate data frame, outside the ggplot
call. That is not be strictly necessary, but I prefer it as I find that it avoids confusion.
Using an x value of 1.5 for the text label works here, as would setting it to "a" if you wanted it directly on the plotted x values.
The error you're describing suggests to me a simple syntax error somewhere in your code (which you haven't completely provided). Perhaps this example will help you to spot it.
精彩评论