nit
nit

Reputation: 689

Simple line plot using R ggplot2

I have data as follows in .csv format as I am new to ggplot2 graphs I am not able to do this

T           L
141.5453333 1
148.7116667 1
154.7373333 1
228.2396667 1
148.4423333 1
131.3893333 1
139.2673333 1
140.5556667 2
143.719     2
214.3326667 2
134.4513333 3
169.309     8
161.1313333 4

I tried to plot a line graph using following graph

data<-read.csv("sample.csv",head=TRUE,sep=",")

ggplot(data,aes(T,L))+geom_line()]

but I got following image it is not I want

enter image description here

I want following image as follows

enter image description here

Can anybody help me?

Upvotes: 0

Views: 223

Answers (2)

fabians
fabians

Reputation: 3473

You want to use a variable for the x-axis that has lots of duplicated values and expect the software to guess that the order you want those points plotted is given by the order they appear in the data set. This also means the values of the variable for the x-axis no longer correspond to the actual coordinates in the coordinate system you're plotting in, i.e., you want to map a value of "L=1" to different locations on the x-axis depending on where it appears in your data.

This type of fairly non-sensical thing does not work in ggplot2 out of the box. You have to define a separate variable that has a proper mapping to values on the x-axis ("id" in the code below) and then overwrite the labels with the values for "L".

The coe below shows you how to do this, but it seems like a different graphical display would probbaly be better suited for this kind of data.

data <- as.data.frame(matrix(scan(text="
141.5453333 1
148.7116667 1
154.7373333 1
228.2396667 1
148.4423333 1
131.3893333 1
139.2673333 1
140.5556667 2
143.719     2
214.3326667 2
134.4513333 3
169.309     8
161.1313333 4
"), ncol=2, byrow=TRUE))
names(data) <- c("T", "L")
data$id <- 1:nrow(data)
ggplot(data,aes(x=id, y=T))+geom_line() + xlab("L") +
    scale_x_continuous(breaks=data$id, labels=data$L)

enter image description here

Upvotes: 1

Michele
Michele

Reputation: 8753

You have an error in your code, try this:

ggplot(data,aes(x=L, y=T))+geom_line()

Default arguments for aes are:

aes(x, y, ...)

Upvotes: 0

Related Questions