Label stacked bar chart with variable other than plotted Y - r

I'm working on some fish electroshocking data and looking at fish species abundance per transects in a river. Essentially, I have an abundance of different species per transect that I'm plotting in a stacked bar chart. But, what I would like to do is label the top of the bar, or underneath the x-axis tick mark with N = Total Preds for that particular transect. The abundance being plotted is the number of that particular species divided by the total number of fish (preds) that were caught at that transect. I am having trouble figuring out a way to do this since I don't want to label the plot with the actual y-value that is being plotted.
Excuse the crude code. I am newer to R and not super familiar with generating random datasets. The following is what I came up with. Obviously in my real data the abundance % per transect always adds up to 100 %, but the idea is to be able to label the graph with TotalPreds for a transect.
#random data
Transect<-c(1:20)
Habitat<-c("Sand","Gravel")
Species<-c("Smallmouth","Darter","Rock Bass","Chub")
Abund<-runif(20,0.0,100.0)
TotalPreds<-sample(1:139,20,replace=TRUE)
data<-data.frame(Transect,Habitat,Species,Abund,TotalPreds)
#Generate plot
AbundChart<-ggplot(data=data,aes(x=Transect,y=Abund,fill=Species))
AbundChart+labs(title="Shocking Fish Abundance")+theme_bw()+
scale_y_continuous("Relative Abundance (%)",expand=c(0.02,0),
breaks=seq(0,100,by=20),labels=seq(0,100,by=20))+
scale_x_discrete("Transect",expand=c(0.03,0))+
theme(plot.title=element_text(face='bold',vjust=2,size=25))+
theme(legend.title=element_text(vjust=5,size=15))+
geom_bar(stat="identity",colour="black")+
facet_grid(~Habitat,labeller=label_both,scales="free_x")
I get this plot that I would like to label with TotalPreds as described previously.
Again my plot would have bars that reached 100% for abundance, and in my real data transects 1-10 are gravel and 11-20 are sand. Excuse my poor sample dataset.
*Update
My actual data looks like this:
Variable in this case is the fish species and value is the abundance of that species at that particular electroshocking transect. Total_Preds is repeated when the data moves to a new species, because total preds is indicative of the total preds caught at that particular transect (i.e. each transect only has 1 total preds value). Maybe the melt function wasn't the right way to analyze this, but I have like 17 fish species that were caught at different rates across these 20 transects. I guess habitat type is singular to a transect as well, with 1-10 being gravel and 11-20 being sand, and that is repeated in my dataset across fish species as well.

Edited in response to the update, you should be able to create a new dataframe containing the TotalPred data (not repeated) and use that in geom_text. Can't test this without data but maybe:
# select non-repeated half of melted data for use in geom_text
textlabels <- data[c(1:19),]
#Generate plot
AbundChart<-ggplot(data=data,aes(x=Transect,y=Abund,fill=Species))
AbundChart+labs(title="Shocking Fish Abundance")+theme_bw()+
scale_y_continuous("Relative Abundance (%)",expand=c(0.02,0),breaks=seq(0,100,by=20),labels=seq(0,100,by=20))+
scale_x_discrete("Transect",expand=c(0.03,0))+
theme(plot.title=element_text(face='bold',vjust=2,size=25))+
theme(legend.title=element_text(vjust=5,size=15))+
geom_bar(stat="identity",colour="black")+
facet_grid(~Habitat,labeller=label_both,scales="free_x") +
geom_text(data = textlabels, aes(x = Transect_ID, y = value, vjust = -0.5,label = TotalPreds))
You might have to play around with different values for vjust to get the labels where you want them.
See the geom_text help page for more info.
Hope that edit works with your data.

Related

Plotting proportions of choices of each participant separately

I's like to find a quite efficient way to plot for each participant ($participant_num) the proportion of responses ($resp) every 10 trials ($trial, out of 200 trials per participant).
enter image description here
When I did it for a subset of my sample (only 30 participants) I used a very rudimental code, for which I had first created a separate dataframe for each subject:
whichSubject<-6 # Which subject do want to analyse?
sData<-filter(banditData,subject==whichSubject)
and then I tried to get proportions for each 10 trials and put them in a separate column
sData$newcolumn <- NULL
sData$newcolumn1_10<- table(sData[1:10,]$resp)/length(sData[1:10,]$resp)
sData$newcolumn11_20<- table(sData[11:20,]$resp)/length(sData[11:20,]$resp)
sData$newcolumn21_30<- table(sData[21:30,]$resp)/length(sData[21:30,]$resp)
and so on for all the 200 trials and separately for each subject.. Then, I reshaped the dataframe as long and plotted it with the following script:
ggplot()+
geom_line(data=rewardDF,aes(x=Trial,y=pHappy,colour=Bandit), linetype="dashed", size=1.03)+
geom_point(data=longdf,aes(x=trial, y=resp_prop,colour=bandit,shape=bandit),size=3)+
geom_line(data=longdf,aes(x=trial, y=resp_prop,colour=bandit),size=1)+
scale_shape_manual(values=SymTypes)+
scale_colour_manual(values=cbPalette)+
labs(col='bandit',y='p(choice)',x='trials')+
scale_x_continuous(breaks = seq(0,200,by=10), limits=c(0,203), expand=(c(0,0)))+
scale_y_continuous(breaks = seq(0,1,by=0.1), limits=c(0,1.03), expand=(c(0.02,0)))+
theme_bw()+
ggsave(paste(c("data/S",whichSubject,"p(choice_absorangeblue).png"),collapse=""), scale=2,dpi = 300)
The output was something like this. Each dot represented how many times a participant selected left (resp=0) vs right (resp=1) in 10 trials (e.g., if the participant selected left 3 times out of 10 the dot for left, which corresponded to arm 1 in a task where you were asked to select between two arms, would be presented on the y axis at 0.3 and conversly the dot for right at 0.7)
enter image description here
However, now I have over 200 participants and it is definitely too time consuming using this approach!
I was thinking of using something to add facet_grid(participant_num ~ .)+ to my ggplot code in order to code each participant separately without the need of sub selecting.. However, I haven't found a solution on how to plot the proportion of choices without having to calculate them separately. Do you have any tip on how I could do this within ggplot?
Many thanks in advance for your help!!

Add points to geom_density_ridges for groups with small number of observations

I am loving using geom_density_ridges(), with individual points also included for each group. However, some groups have small sample sizes (e.g. n=1 or 2) precluding the generation of the density ridges. For these groups, I'd like to be able to plot the locations of the existing observations - even though no probability density function will be shown.
In this example, I'd like to be able to plot the 2 data points for May on the appropriate line.
library(tidyverse)
library(ggridges)
data("lincoln_weather")
#pull weather from all months that are NOT May
lincoln_weather_nomay<-lincoln_weather[which(lincoln_weather$Month!="May"),]
#pull weather just from May
lincoln_weather_may<-lincoln_weather[which(lincoln_weather$Month=="May"),]
#recombine, keeping only the first two rows for the May dataset
new_weather<-rbind(lincoln_weather_nomay,lincoln_weather_may[c(1:2),])
ggplot( new_weather, aes(x=`Min Temperature [F]`,y=Month,fill=Month))+
geom_density_ridges(alpha = 0.5,jittered_points = TRUE, point_alpha=1,point_shape=21) +
labs(x="Average temperature (F)",y='')+
guides(fill=FALSE,color=FALSE)
How can I add the points for the May observations to the appropriate location (i.e. the May slot) and at the appropriate location along the x-axis?
Simply add a separate geom_point() call to the function, in which you subset the data to include only observations for the previously-unplotted categories. You can apply any of the usual customizations to either 'match' the points plotted for the other categories, or to make these points 'stand out'.
ggplot( new_weather, aes(x=`Min Temperature [F]`,y=Month,fill=Month))+
geom_density_ridges(alpha = 0.5,jittered_points = TRUE, point_alpha=1,point_shape=21) +
geom_point(data=subset(new_weather, Month %in% c("May")),
aes(),shape=13)+
labs(x="Average temperature (F)",y='')+
guides(fill=FALSE,color=FALSE)

plotting multiple lines in ggplot R

I have neuroscientific data where we count synapses/cells in the cochlea and quantify these per frequency. We do this for animals of different ages. What I thus ideally want is the frequencies (5,10,20,30,40) in the x-axis and the amount of synapses/cells plotted on the y-axis (usually a numerical value from 10 - 20). The graph then will contain 5 lines of the different ages (6 weeks, 17 weeks, 43 weeks, 69 weeks and 96 weeks).
I try this with ggplot and first just want to plot one age. When I use the following command:
ggplot(mydata, aes(x=Frequency, y=puncta6)) + geom_line()
I get a graph, but no line and the following error: 'geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?'
So I found I have to adjust the code to:
ggplot(mydata, aes(x=Frequency, y=puncta6, group = 1)) + geom_line()
This works, except for the fact that my first data point (5 kHz) is now plotted behind my last data point (40 kHz)......... (This also happens without the 'group = 1' addition). How do I solve this or is there an easier way to plot this kind of data?
I couldnt add a file so I added a photo of my code + graph with the 5 kHz data point oddly located and I added a photo of my data in excel.
example data
example code and graph

How to plot multiple variables with means as y values for multiple groups in r?

I have already researched the webs on how to do this but nothing has worked - there is an element missing always. I am trying to plot histogram for mean fish condition (y axis) for males and females(colour/legend) for each age group(x axis). What complicates it more is that I have multiple sites so I am not sure how to go about it. I have attached what is kind of close to what I had like to plot(note how a factor is missing-sites). There is a lot of code I have tried but I will provide a sample below. My data is saved as a csv with different columns that have sex, site, fish condition, etc.
F8 is the csv sheet that has multiple sites from one year
K is the fish condition column that I want means calculated for
gender.mean <- t(tapply(F8$K,
list(F8$Age1, F8$Sex), mean))
^I am not sure how to factor in the site as well.
I plotted this (code below) which gives me mean condition for both males and females for each age group but its all of sites combined.
barplot(gender.mean, col=c("darkblue","red"), beside=TRUE, legend=c("F","M"))
^for some reason, the x axis line (not numbers) is missing though and the legend is on top of the bars?
In addition, I had like the bars to have standard error bars but
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3)
the above code has not worked.

Plotting multiple frequency polygon lines using ggplot2

I have a dataset with records that have two variables: "time" which are id's of decades, and "latitude" which are geographic latitudes. I have 7 time periods (numbered from 26 to 32).
I want to visualize a potential shift in latitude through time. So what I need ggplot2 to do, is to plot a graph with latitude on the x-axis and the count of records at a certain latitude on the y-axis. I need it do this for the seperate time periods and plot everything in 1 graph.
I understood that I need the function freqpoly from ggplot2, and I got this so far:
qplot(latitude, data = lat_data, geom = "freqpoly", binwidth = 0.25)
This gives me the correct graph of the data, ignoring the time. But how can I implement the time? I tried subsetting the data, but I can't really figure out if this is the best way..
So basically I'm trying to get a graph with 7 lines showing the frequency distribution in each decade in order to look for a latitude shift.
Thanks!!
Without sample data it is hard to answer but try to add color=factor(time) (where time is name of your column with time periods). This will draw lines for each time period in different color.
qplot(latitude, data = lat_data, geom = "freqpoly", binwidth = 0.25,
color=factor(time))

Resources