简体   繁体   中英

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

在此处输入图片说明

I want following image as follows

在此处输入图片说明

Can anybody help me?

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, ie, 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)

在此处输入图片说明

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, ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM