building a area plot in R - r

I´m trying to build a graph that plots relative abundance against depth variation.
I have the following table
test X1m X2m X3m X4m X5m X6m X7m
1 Example1 1 10 10 1 1 5 1
2 Example2 2 5 5 5 2 2 5
and I have tried the following using ggplot2()
Example.class.melt<-melt(Example.df)
colnames(Example.class.melt)[1] = "Class"
colnames(Example.class.melt)[2] = "Depth"
colnames(Example.class.melt)[3] = "Relative_abundance"
Example.class.melt<-as.data.frame(Example.class.melt)
ggplot(Example.class.melt, aes(x=Depth, y=Relative_abundance, fill=as.factor(Class))) + geom_area()
For some reason, that I don´t understand, it isn´t working. Any suggestion to correct this or any alternative?
thanks

Is this what you are looking for?This was my interpretation based on the way you asked the question. The code is as follows:
install.packages("ggplot2")
install.packages("reshape")
library(ggplot2)
library(reshape)
Example1<-c(1,10,10,1,1,5,1)
Example2<-c(2,5,5,5,2,2,5)
data<-rbind(Example1,Example2)
Example.class.melt<-melt(data)
colnames(Example.class.melt)[1] = "Class"
colnames(Example.class.melt)[2] = "Depth"
colnames(Example.class.melt)[3] = "Relative_abundance"
Example.class.melt<-as.data.frame(Example.class.melt)
ggplot(data = Example.class.melt, aes(x = Depth, y = Relative_abundance, fill=Class)) + geom_area()
You don't require to say as.factor in fill to class.

Related

ggplot not reading dataframe the way I expected

Recently I've been trying to plot some data using ggplot that's defined like so. (Essentially assigning a different x value to two different data sets and using the y axis to display the points)
xcol = c(rep(2, length(allTTRs(teamset))))
ycol = c(allTTRs(teamset))
xcol2 = c(rep(1, length(allTTRs(oldteamset))))
ycol2 = c(allTTRs(oldteamset))
masterY = append(ycol, ycol2)
masterX = append(xcol, xcol2)
mat = cbind(masterX, masterY)
df = as.data.frame(mat)
show(df)
The show() call outputs this
masterX masterY
1 2 10.998817
2 2 10.999933
3 2 37.001567
4 2 15.016150
5 1 2.000817
6 1 5.000150
7 1 13.995800
8 1 11.001933
9 1 24.987017
10 1 0.999850
11 1 2.998750
Next I plot this data like so
p <- ggplot(data = df, mapping = aes(x = masterX, y = masterY)) +
geom_dotplot(inherit.aes = TRUE, binwidth = 0.005, data = df, y = masterY, show.legend=TRUE) +
stat_summary(fun.data = mean_sdl, color = "red")
When I run this, something strange happens. It seems the stat_summary() plots perfectly, but for some reason the geom_dotplot() call transposes the x values, such that the graph looks like this
It occurred to me this may be because I specify a 'y' argument in geom_dotplot but no 'x' argument, so I tried including 'x=masterX' in its arguments, but when I do that I get this error.
Error: stat_bindot requires the following missing aesthetics: x
Strangely, when I delete the 'y' argument from the function, I get a similar error for 'y' for the opposite reason. I.e.
Error: geom_dotplot requires the following missing aesthetics: y
Ultimately, I've already fixed this problem by changing masterY/X definitions like so
masterY = append(ycol2, ycol)
masterX = append(xcol2, xcol)
But this is rather unsatisfying to me, since I know it's still not using the x values as tuples, and is instead simply plotting based on the order of the dataframe, and I'd like to learn how to deal with intermixed data for the future. Ultimately, I get the feeling I'm misusing a function or doing something very non-idiomatically, but I'm not sure what.
Could anyone explain why this is happening and/or how I could use ggplot to graph data that might look more like so?
masterX masterY
1 2 10.998817
2 2 10.999933
3 2 37.001567
4 1 2.000817
5 2 15.016150
6 1 5.000150
7 1 13.995800
8 1 11.001933
9 1 24.987017
10 1 0.999850
11 1 2.998750
I think this will get you what you want:
ggplot(df, aes(x = masterX, y = masterY)) +
geom_point() +
stat_summary(fun.data = mean_sdl, color = "red")

2d plot with 3rd variable as color in RStudio

I have a dataset as CSV with three columns:
timestamp (e.g. 2018/12/15)
keyword (e.g. "hello")
count (e.g. 7)
I want one plot where all the lines of the same keyword are connected with each other and timestamp is on the X- and count is on the Y- axis. I would like each keyword to have a different color for its line and the line being labeled with the keyword.
The CSV has only ~30.000 rows and R runs on a dedicated machine. Performance can be ignored.
I tried various approaches with mathplot and ggplot in this forum, but didn't get it to work with my own data.
What is the easiest solution to do this in R?
Thanks!
EDIT:
I tried customizing Romans code and tried the following:
`csvdata <- read.csv("c:/mydataset.csv", header=TRUE, sep=",")
time <- csvdata$timestamp
count <- csvdata$count
keyword <- csvdata$keyword
time <- rep(time)
xy <- data.frame(time, word = c(keyword), count, lambda = 5)
library(ggplot2)
ggplot(xy, aes(x = time, y = count, color = keyword)) +
theme_bw() +
scale_color_brewer(palette = "Set1") + # choose appropriate palette
geom_line()`
This creates a correct canvas, but no points/lines in it...
DATA:
head(csvdata)
keyword count timestamp
1 non-distinct-word 3 2018/08/09
2 non-distinct-word 2 2018/08/10
3 non-distinct-word 3 2018/08/11
str(csvdata)
'data.frame': 121 obs. of 3 variables:
$ keyword : Factor w/ 10 levels "non-distinct-word",..: 5 5 5 5 5 5 5 5 5 5 ...
$ count : int 3 2 3 1 6 6 2 3 2 1 ...
$ timestamp: Factor w/ 103 levels "2018/08/09","2018/08/10",..: 1 2 3 4 5 6 7 8 9 10 ...
Something like this?
# Generate some data. This is the part poster of the question normally provides.
today <- as.Date(Sys.time())
time <- rep(seq.Date(from = today, to = today + 30, by = "day"), each = 2)
xy <- data.frame(time, word = c("hello", "world"), count = rpois(length(time), lambda = 5))
library(ggplot2)
ggplot(xy, aes(x = time, y = count, color = word)) +
theme_bw() +
scale_color_brewer(palette = "Set1") + # choose appropriate palette
geom_line()

Trying to make a bar chart with each categorical column as a different color

I found a cool Wes Anderson palette package but I am failing here in actually using it. The variable I am looking at (Q1) has options 1 and 2. There is an NA in the set which is getting plotted however I would like to remove it as well.
library(readxl)
library(tidyverse)
library(wesanderson)
RA_Survey <- read_excel("file extension")
ggplot(data = RA_Survey, mapping = aes(x = Q1)) +
geom_bar() + scale_fill_manual(values=wes_palette(n=2, name="GrandBudapest"))
The plot I'm getting is working but without the color. Any ideas?
There are several issues which need to be addressed.
Using the Wes Anderson palette
As already mentioned by Mako, the fill aesthetic was missing from the call to aes().
Furthermore, the OP reports an error message saying Palette not found. The wesanderson package contains a list of available palettes:
names(wesanderson::wes_palettes)
[1] "BottleRocket1" "BottleRocket2" "Rushmore1" "Rushmore" "Royal1" "Royal2" "Zissou1"
[8] "Darjeeling1" "Darjeeling2" "Chevalier1" "FantasticFox1" "Moonrise1" "Moonrise2" "Moonrise3"
[15] "Cavalcanti1" "GrandBudapest1" "GrandBudapest2" "IsleofDogs1" "IsleofDogs2"
There is no palette called "GrandBudapest" as requested in OP's code. Instead, we have to choose between "GrandBudapest1" and "GrandBudapest2".
Also, the help file help("wes_palette") lists the available palettes.
Here is a working example which uses the dummy data created in the Data section below:
library(ggplot2)
library(wesanderson)
ggplot(RA_Survey, aes(x = Q1, fill = Q1)) +
geom_bar() +
scale_fill_manual(values=wes_palette(n=2, name="GrandBudapest1"))
Removing NA
The OP has asked to remove the NAs from the set. There are two options:
Tell ggplot() to remove the NAs.
Remove the NAs from te data by filtering.
We can tell ggplot() to remove NAs when plotting the x axis:
library(ggplot2)
library(wesanderson)
ggplot(RA_Survey, aes(x = Q1, fill = Q1)) +
geom_bar() +
scale_fill_manual(values=wes_palette(n=2, name="GrandBudapest1")) +
scale_x_discrete(na.translate = FALSE)
Note, this produces a warning message Removed 3 rows containing non-finite values (stat_count). To get rid of the message, we can use geom_bar(na.rm = TRUE).
The other option removes the NAs from the data by filtering
library(dplyr)
library(ggplot2)
library(wesanderson)
ggplot(RA_Survey %>% filter(!is.na(Q1)), aes(x = Q1, fill = Q1)) +
geom_bar() +
scale_fill_manual(values=wes_palette(n=2, name="GrandBudapest1"))
which creates exactly the same chart.
Data
As the OP has not provided a sample dataset, we need to create our own:
library(dplyr)
set.seed(123L)
RA_Survey <- data_frame(Q1 = sample(c("1", "2", NA), 20, TRUE, c(3, 6, 1)))
RA_Survey
# A tibble: 20 x 1
Q1
<chr>
1 2
2 1
3 2
4 1
5 NA
6 2
7 2
8 1
9 2
10 2
11 NA
12 2
13 1
14 2
15 2
16 1
17 2
18 2
19 2
20 NA

Reasons that ggplot2 legend does not appear [duplicate]

This question already has answers here:
Add legend to ggplot2 line plot
(4 answers)
Closed 2 years ago.
I was attempting (unsuccessfully) to show a legend in my R ggplot2 graph which involves multiple plots. My data frame df and code is as follows:
Individuals Mod.2 Mod.1 Mod.3
1 2 -0.013473145 0.010859793 -0.08914021
2 3 -0.011109863 0.009503278 -0.09049672
3 4 -0.006465788 0.011304668 -0.08869533
4 5 0.010536718 0.009110458 -0.09088954
5 6 0.015501212 0.005929766 -0.09407023
6 7 0.014565584 0.005530390 -0.09446961
7 8 -0.009712516 0.012234843 -0.08776516
8 9 -0.011282278 0.006569570 -0.09343043
9 10 -0.011330579 0.003505439 -0.09649456
str(df)
'data.frame': 9 obs. of 4 variables:
$ Individuals : num 2 3 4 5 6 7 8 9 10
$ Mod.2 : num -0.01347 -0.01111 -0.00647 0.01054 0.0155 ...
$ Mod.1 : num 0.01086 0.0095 0.0113 0.00911 0.00593 ...
$ Mod.3 : num -0.0891 -0.0905 -0.0887 -0.0909 -0.0941 ...
ggplot(df, aes(df$Individuals)) +
geom_point(aes(y=df[,2]), colour="red") + geom_line(aes(y=df[,2]), colour="red") +
geom_point(aes(y=df[,3]), colour="lightgreen") + geom_line(aes(y=df[,3]), colour="lightgreen") +
geom_point(aes(y=df[,4]), colour="darkgreen") + geom_line(aes(y=df[,4]), colour="darkgreen") +
labs(title = "Modules", x = "Number of individuals", y = "Mode")
I looked up the following stackflow threads, as well as Google searches:
Merging ggplot2 legend
ggplot2 legend not showing
`ggplot2` legend not showing label for added series
ggplot2 legend for geom_area/geom_ribbon not showing
ggplot and R: Two variables over time
ggplot legend not showing up in lift chart
Why ggplot2 legend not show in the graph
ggplot legend not showing up in lift chart.
This one was created 4 days ago
This made me realize that making legends appear is a recurring issue, despite the fact that legends usually appear automatically.
My first question is what are the causes of a legend to not appear when using ggplot? The second is how to solve these causes. One of the causes appears to be related to multiple plots and the use of aes(), but I suspect there are other reasons.
colour= XYZ should be inside the aes(),not outside:
geom_point(aes(data, colour=XYZ)) #------>legend
geom_point(aes(data),colour=XYZ) #------>no legend
Hope it helps, it took me a hell long way to figure out.
You are going about the setting of colour in completely the wrong way. You have set colour to a constant character value in multiple layers, rather than mapping it to the value of a variable in a single layer.
This is largely because your data is not "tidy" (see the following)
head(df)
x a b c
1 1 -0.71149883 2.0886033 0.3468103
2 2 -0.71122304 -2.0777620 -1.0694651
3 3 -0.27155800 0.7772972 0.6080115
4 4 -0.82038851 -1.9212633 -0.8742432
5 5 -0.71397683 1.5796136 -0.1019847
6 6 -0.02283531 -1.2957267 -0.7817367
Instead, you should reshape your data first:
df <- data.frame(x=1:10, a=rnorm(10), b=rnorm(10), c=rnorm(10))
mdf <- reshape2::melt(df, id.var = "x")
This produces a more suitable format:
head(mdf)
x variable value
1 1 a -0.71149883
2 2 a -0.71122304
3 3 a -0.27155800
4 4 a -0.82038851
5 5 a -0.71397683
6 6 a -0.02283531
This will make it much easier to use with ggplot2 in the intended way, where colour is mapped to the value of a variable:
ggplot(mdf, aes(x = x, y = value, colour = variable)) +
geom_point() +
geom_line()
ind = 1:10
my.df <- data.frame(ind, sample(-5:5,10,replace = T) ,
sample(-5:5,10,replace = T) , sample(-5:5,10,replace = T))
df <- data.frame(rep(ind,3) ,c(my.df[,2],my.df[,3],my.df[,4]),
c(rep("mod.1",10),rep("mod.2",10),rep("mod.3",10)))
colnames(df) <- c("ind","value","mod")
Your data frame should look something likes this
ind value mod
1 5 mod.1
2 -5 mod.1
3 3 mod.1
4 2 mod.1
5 -2 mod.1
6 5 mod.1
Then all you have to do is :
ggplot(df, aes(x = ind, y = value, shape = mod, color = mod)) +
geom_line() + geom_point()
I had a similar problem with the tittle, nevertheless, I found a way to show the title: you can add a layer using
ggtitle ("Name of the title that you want to show")
example:
ggplot(data=mtcars,
mapping = aes(x=hp,
fill = factor(vs)))+
geom_histogram(bins = 9,
position = 'identity',
alpha = 0.8, show.legend = T)+
labs(title = 'Horse power',
fill = 'Vs Motor',
x = 'HP',
y = 'conteo',
subtitle = 'A',
caption = 'B')+
ggtitle("Horse power")

ggmap and scale_colour_brewer

I am trying to plot a frequency over a map obtained with ggmap in R. The idea is that I would have a plot of the frequency on each coordinates set. The frequency ("freq") would be mapped to six and a color scale. The data looks like this:
V7 V6 freq
1 42.1752 -71.2893 1
2 42.1754 -71.2893 1
3 42.1755 -71.2901 2
4 42.1755 -71.2893 1
5 42.1756 -71.2910 1
6 42.1756 -71.2907 1
7 42.1756 -71.2906 1
8 42.1756 -71.2905 1
9 42.1756 -71.2901 1
10 42.1756 -71.2899 2
11 42.1756 -71.2897 2
12 42.1756 -71.2894 2
13 42.1757 -71.2915 1
14 42.1757 -71.2910 1
Here is the code I am using:
ggmap(newmap2) +
geom_point(aes(x = coordfreq$V7, y = coordfreq$V6),
data = coordfreq, alpha = 1/sqrt(coordfreq$freq),
colour = coordfreq$freq, size = sqrt(coordfreq$freq)) +
scale_colour_brewer(palette = "Set1")
I only get the color mapped to "freq", but I cannot get the scale_colour_brewer to work. I have tried several arguments to scale_color_brewer to no available.
Your code created a map without data points. Here is possibly what you are after. A few things. One is that you do not have to type x = coordfreq$V7. You can just type x = V7. The same applies to other similar cases in your code. Another is that colour should be in aes() in your case. Another thing is that freq is numeric. You need it as either factor or character when you assign colours to your graphic. The other is that freq is a function. You want to void such a name. Hope this will help you.
library(ggmap)
library(ggplot2)
# This get_map code was suggested by an SO user. Sadly, the edit was rejected.
# Credit to him/her (MichaelVE).
newmap2 <- get_map(location = c(lon = -71.2893, lat = 42.1752),
zoom = 17, maptype = 'terrain')
ggmap(newmap2) +
geom_point(data = mydf2, aes(x = V6, y = V7, colour = factor(frequency), size = sqrt(frequency))) +
scale_colour_brewer(palette ="Set1")

Resources