0

What is the best way to plot points having coordinates in the same column with R?

For instance, having this dataframe :

 df <- data.frame(city=c("Paris", "Paris", "New-York", "New-York"), year=c(2010,2016,2010,2016), val=c(10,-10,100,-100))

     city  year  val
1    Paris 2010   10
2    Paris 2016  -10
3 New-York 2010  100
4 New-York 2016 -100

I want to have a plot using val of 2010 on the x-axis and val of 2016 on the y-axis (that is Paris at 10,-10 and New-York at 100,-100): plot example

What I usually do is subsetting/merging to have different columns :

df.2010 <- df[df$year == 2010, c("city","val")]
colnames(df.2010) <- c("city","val.2010")
df.2016 <- df[df$year == 2016, c("city","val")]
colnames(df.2016) <- c("city","val.2016")
df.m <- merge(df.2010, df.2016)

Giving :

       city val.2010 val.2016
 1 New-York      100     -100
 2    Paris       10      -10

And then:

 ggplot(df.m, aes(x=val.2010,y=val.2016,label=city)) + geom_label()

But I found this method inelegant and also very heavy with bigger data. Does anyone know a better way to achieve the same goal? Either by better using ggplot or subsetting/merging more elegantly, perhaps?

Many thanks!

Julien
  • 3
  • 1
  • The reshape package will help you out: `https://seananderson.ca/2013/10/19/reshape/` – Chris Nov 19 '18 at 22:55
  • `ggplot` generally wants data in the long format that have, but in this case your data is actually _too_ long. Cast it to wide as described here: [How to reshape data from long to wide format?](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format) – Henrik Nov 19 '18 at 23:01

1 Answers1

1

You can use the tidyverse spread function, so using your example:

library(tidyverse)
df <- data.frame(city=c("Paris", "Paris", "New-York", "New-York"), year=c(2010,2016,2010,2016), val=c(10,-10,100,-100))
df1 <- spread(df, "year", "val")
ggplot(df1, aes(x=`2010`,y=`2016`,label=city)) + geom_label()
GordonShumway
  • 1,980
  • 13
  • 19
  • Thank you very much! And very sorry for the duplicate, expressing the question was not easy at all. – Julien Nov 20 '18 at 08:33