简体   繁体   中英

How to draw a graph in R language with labels in X-axis

I have the following data in .csv file:

Name  marks1 marks2    
xy      10    30
yz      20    40
zx      30    40
vx      20    20
vt      10    20

How do I draw a graph with both marks1 and marks2 in y-axis and name in x-axis?

y <- cbind(data$marks1,data$marks2)
x <- cbind(data$Name)
matplot(x,y,type="p")

Here is one possibility using ggplot:

## Creating your dataset
Name <-c("xy","yz","zx","vx","vt")
marks1 <- c(10,20,30,20,10)
marks2 <- c(30,40,40,20,20)

## Combine the data into a data frame
data <- data.frame(Name,marks1,marks2)

## Loading libraries 
library(ggplot2)
library(reshape2)

## Reshape the data from wide format to long format
redata <- melt(data,id="Name")
redata

## plot your data 
ggplot(redata,aes(x=Name,y=value))+geom_point(aes(color=variable))+ylab("Marks")

The output is as follows:

在此处输入图片说明

Updated for the file read

If you have a file with the above data then you can read your data using the following command: I am assuming your file has a extension *.csv and is spaced by commas.

data <- read.table("mydata.csv",header=T,sep=",")

or you directly use the following code for csv files

data <- read.csv("mydata.csv")

After that you can go to libraries part in my above answer.

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