0

I got the following CSV input file (column are separated by tab):

fruits     A      B     C
apple      9.8    21    62.2
bananas    12     11    58.3
pineapple  3.5    13    41.2
kiwi       6.4    36.5  38.1
strawberry 2.5    47.2  35.5

But did not managed to plot the graph using ggplot. Instead of this I created the same input but a bit different

fruits      Who How Much
apple       A   9.8
bananas     A   12
pineapple   A   3.5
kiwi        A   6.4
strawberry  A   2.5
apple       B   21
bananas     B   11
pineapple   B   13
kiwi        B   36.5
strawberry  B   47.2
apple       C   62.2
bananas     C   58.3
pineapple   C   41.2
kiwi        C   38.1
strawberry  C   35.5

Then i read the data

data <- read.table(file.choose(), header = TRUE, sep= '\t')

and plotted it with

ggplot(data=data, aes(x=Who, y=HowMuch, group=Fruits, colour=Fruits)) + 
       geom_line() + geom_point() + ggtitle("Fruits") + theme_bw() + 
       theme(legend.position=c(.9, .3)) + theme(legend.title=element_blank())

How can I do the same plot using my original input file from the beginning of the post ? Without creating the new input file..

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
Maca
  • 9
  • The general approach in ggplot2 is to work with data in a long format instead of a wide format. You can do the reshaping after reading the data in rather than making a different input file via, e.g., `reshape2::melt`. Lots of examples on SO, including [this answer](http://stackoverflow.com/a/3777592/2461552) – aosmith Aug 19 '16 at 18:34

2 Answers2

2

obligatory tidyverse solution:

library(tidyr)

read.table(text="fruits     A      B     C
apple      9.8    21    62.2
bananas    12     11    58.3
pineapple  3.5    13    41.2
kiwi       6.4    36.5  38.1
strawberry 2.5    47.2  35.5", header=TRUE, stringsAsFactors=FALSE) -> df

gather(df, who, how_much, -fruits) 
hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
1
fruits<-c("apple","bananas","pineapple","kiwi","strawberry")
A<-c("9.8","12","3.5","6.4","2.5")
B<-c("21","11","13","36.5","47.2")
C<-c("62.2","58.3","41.2","38.1","35.5")

df<-data.frame(fruits, A, B, C)
df
      fruits   A    B    C
1      apple 9.8   21 62.2
2    bananas  12   11 58.3
3  pineapple 3.5   13 41.2
4       kiwi 6.4 36.5 38.1
5 strawberry 2.5 47.2 35.5

library(reshape2)
melt(df, id="fruits")

       fruits variable value
1       apple        A   9.8
2     bananas        A    12
3   pineapple        A   3.5
4        kiwi        A   6.4
5  strawberry        A   2.5
6       apple        B    21
7     bananas        B    11
8   pineapple        B    13
9        kiwi        B  36.5
10 strawberry        B  47.2
11      apple        C  62.2
12    bananas        C  58.3
13  pineapple        C  41.2
14       kiwi        C  38.1
15 strawberry        C  35.5
Cyrus Mohammadian
  • 4,982
  • 6
  • 33
  • 62