1

How do I connect specific points on a plot using ggplot, based on the values of certain columns? I have the solution to this problem using the base plotting system, but I want to know how this task can be done using ggplot.

Code for accomplishing this task using the base plotting system:

#Defining the dataset
states <- letters[1:10]
set.seed(12345)
profit.2010 <- runif(10, 1000, 2000)
profit.2011 <- runif(10, 1000, 2000)
data <- data.frame(states, profit.2010, profit.2011)

#Making a plot using base plotting system
par(mfrow = c(1, 1))
with(data, plot(rep(1, 10), data[, 2], xlim = c(.5, 2.5)))
with(data, points(rep(2, 10), data[, 3]))
segments(rep(1, 10), data[, 2], rep(2, 10), data[, 3])

Incomplete code using ggplot. I have plotted the points. Now how to join these points using ggplot?

library(tidyr)
dat <- tbl_df(data)
dat <- dat %>%
        gather(year, profit, -states)
ggplot(dat, aes(year, profit)) + geom_text(aes(label = states))

1 Answer 1

1

If you want lines, add a geom_line and set the group= aesthetic so it knows which points to connect.

ggplot(dat, aes(year, profit)) + 
    geom_text(aes(label = states)) + 
    geom_line(aes(group = states))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.