Reputation: 9
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..
Upvotes: 0
Views: 47
Reputation: 78832
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)
Upvotes: 2
Reputation: 5193
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
Upvotes: 1