How do I create a scatter plot with ordered character variables on the x-axis using plot() in r?

Viewed 1324

My data kind of looks like this (except in a table imported from excel):

x values: E, D, D, C, B, A, A

y values: 0, 1, 2, 3, 5, 7, 8

I get 'Error in plot.window(...) : need finite 'xlim' values'. I tried to use plot(factor(x), y, type = "p") and am still getting a line instead of a point and a bar where there are two values for the same variable. Making it an ordered list by using factored<-factor(x), ordered = TRUE then plotting plot(factored, y, type = "p") also seems to have no effect and it defaults to alphabetical.

Any help using the plot function would be great. Thank you!

2 Answers

You need to factor your x variable, so that they are associated with a certain level, e.g A -> 1 , B-> 2 and so on.

You plot using the numeric of the factor and label the x-axis with the levels:

x = c("A","A","B","C","D","D","E")
y = c(0,1,2,3,5,7,8)

x=factor(x)

plot(as.numeric(x),y,xaxt="n")
axis(1,1:length(levels(x)),levels(x))

enter image description here

If you would like them to appear in the order it appears in x and not sorted alphabetically, for example:

x = c("E","D","D","A","A","C","B")
y = c(8,5,7,0,1,3,2)
# or you specify it specifically, levels = c(....)
x=factor(x,levels=unique(x))

plot(as.numeric(x),y,xaxt="n")
axis(1,1:length(levels(x)),levels(x))

enter image description here

If you use package ggplot2, the graph can be plotted even if x is not a factor, like in StupidWolf's answer. Note that I create the data.frame with argument stringsAsFactors = FALSE.

library(ggplot2)

df1 <- data.frame(x, y, stringsAsFactors = FALSE)

ggplot(df1, aes(x, y)) + geom_point() + theme_bw()

enter image description here

Related