0

I have a 7obs x 26 variables dataframe. The observations (rows) are countries, and the columns are years. However, the years are written as the column names.

What I want to do is create a plot that has the years (column names) as X axis and each of the countries as Y axis. So what I do is, first delete the first column with the names.

map1 <- map1[-1]

And then plot:

ggplot(map1, aes(8)) + 
  geom_line(aes(y = 1, colour = "var0")) + 
  geom_line(aes(y = 2, colour = "var1")) +
  geom_line(aes(y = 3, colour = "var0")) + 
  geom_line(aes(y = 4, colour = "var0")) + 
  geom_line(aes(y = 5, colour = "var0")) + 
  geom_line(aes(y = 6, colour = "var0")) + 
  geom_line(aes(y = 7, colour = "var0"))

However this gives me an empty graph

  • Change the `"var0"` to `var0` and similarly the `var1` i.e. unquote – akrun Aug 14 '21 at 23:57
  • It would be easier to help if you create a small reproducible example along with expected output. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Aug 15 '21 at 02:43

1 Answers1

2

As ggplot2 is build on the concept of tidy data, which means that each row is a observation, each column a variable, it's best to reshape your data using e.g. tidyr::pivot_longer:

As you provided no data I make use of some random data based on the gapminder dataset:

library(gapminder)
library(dplyr)
library(tidyr)
library(ggplot2)

map1_tidy <- map1 %>% 
  tidyr::pivot_longer(-country, names_to = "year", values_to = "value")

ggplot(map1_tidy, aes(year, value, color = country, group = country)) +
  geom_line()

DATA

set.seed(42)

map1 <- gapminder[, c("country", "year", "gdpPercap")] %>% 
  tidyr::pivot_wider(names_from = year, values_from = gdpPercap) %>% 
  dplyr::sample_n(10)
stefan
  • 90,330
  • 6
  • 25
  • 51