I want to ask questions whether I could draw graphs with these data.
I have dataset looks like below, (not real data, but it has form of this dataset)
Year 2005 2006 2007 2008 2009 2010 2011
X 0 0 0 1 1 1 1
Y 0 0 0 0 0 3 3
I want to draw a graph with both plot and line, and xaxis with x variable of each year, and Y variable on yaxis.
It is not simply ggplot(dataset, aes(x=X, y=Y))+geom_point()+geom_line()
instead I want it to see the number of X in every year on X axis.
Does R offer these kind of function? or do I have to draw seperate graph of year and X and then X and Y?
Thank you so much in advance!
As noted above, I have tried ggplot2 function.
This should be a comment, but I will take a bit more space to walk through it since there may be some confusion.
This is a classic example of needing to transform your data from wide to long to visualize it. Assuming you have your data as dataset
, you can first use tidy::pivot_longer
to get it in TIdy Data format, then plot:
library(tidyr)
library(dplyr)
library(ggplot2)
dataset %>%
pivot_longer(-Year) %>%
ggplot(aes(x = name, y = value, group = Year)) +
geom_point() +
geom_line()
The pivot_longer(-Year)
takes all the columns except Year
and transforms them to long (run dataset %>% pivot_longer(-Year)
to see what it does).
The resulting figure looks like this, from which you can customize according to you needs:
Data:
dataset <- read.table(text = "Year 2005 2006 2007 2008 2009 2010 2011
X 0 0 0 1 1 1 1
Y 0 0 0 0 0 3 3", h = TRUE)