Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: line plot for discrete x-axis

Tags:

r

ggplot2

I have the following table but after many tries have been unable to plot the data so that the x-axis tick marks line up with the year. I have found solutions to boxplots, but not for geom_line()

How can I make discrete labels for year?

the following solutions did not work

g + scale_x_discrete(limits=c("2013","2014","2015"))
g + scale_x_discrete(labels=c("2013","2014","2015"))
distance_of_moves
  distance moved year
1       2.914961 2013
2       2.437516 2014
3       2.542500 2015

ggplot(data = distance_of_moves, aes(x = year, y = `distance moved`, group = 1)) +
 geom_line(color = "red", linetype = "dashed", size = 1.5) +
 geom_point(color = "red", size = 4, shape = 21, fill = "white") + 
 ylab("Average distance of movement") + 
 xlab("year") 

enter image description here

like image 552
iskandarblue Avatar asked Feb 04 '16 18:02

iskandarblue


People also ask

Can I use a line graph for discrete data?

Line graphs can also be used with a discrete variable on the x-axis. This is appropriate when the variable is ordered (e.g., “small”, “medium”, “large”), but not when the variable is unordered (e.g., “cow”, “goose”, “pig”).

How do you make a line plot in R?

The basic plot command Here, we use type="l" to plot a line rather than symbols, change the color to green, make the line width be 5, specify different labels for the x and y axis, and add a title (with the main argument).

Are line graphs continuous data?

A typical line graph will have continuous data along both the vertical (y-axis) and horizontal (x-axis) dimensions.

What does a line plot look like?

A Line plot can be defined as a graph that displays data as points or check marks above a number line, showing the frequency of each value. Here, for instance, the line plot shows the number of ribbons of each length. – A line plot is often confused with a line graph. A line plot is different from a line graph.


1 Answers

Reproducible example:

data <- data.frame(dist=c(2.914, 2.437, 2.542), year=c(2013, 2014, 2015))
# this ensures that stuff will be ordered appropriately
data$year <- ordered(data$year, levels=c(2013, 2014, 2015))
ggplot(data, aes(x=factor(year), y=dist, group=1)) +
  geom_line() +
  geom_point()

enter image description here

Specifying the year as an ordered factor will ensure that the x axis is ordered appropriately, regardless of the order in which the levels appear (whereas just using "factor(year)" in the plotting aesthetic could lead to issues).

like image 76
Eric Avatar answered Oct 23 '22 00:10

Eric