plot when years are columns in r

If you have a dataset where years are columns and you want to create a plot in R, one approach is to first transform your data into a "tidy" format where each row is an observation and each column is a variable. The tidyr and reshape2 packages are popular tools for data reshaping.

Once your data is in a tidy format, you can use ggplot2 to create a plot. Here's an example:

main.r
library(tidyr)
library(ggplot2)

# Example data
year_data <- data.frame(country = c("A", "B", "C"),
                         "2000" = c(10, 5, 8),
                         "2005" = c(12, 6, 9),
                         "2010" = c(15, 8, 10))

# Convert to tidy format
tidy_data <- gather(year_data, year, value, -country)

# Plot using ggplot2
ggplot(tidy_data, aes(x = year, y = value, group = country, color = country)) +
    geom_line() +
    labs(title = "Example plot with years as columns",
         x = "Year",
         y = "Value")
540 chars
19 lines

In this example, we first use the gather() function from tidyr to convert the data from wide to long format. The year and value columns are created by gathering all the columns except for country.

We then use ggplot2 to create a line plot with the x-axis representing the year, the y-axis representing the value, and different lines/colors for each country. The group = country argument ensures that all data points for a given country are connected by a line. The labs() function is used to add a title and axis labels to the plot.

gistlibby LogSnag