I'm trying to make a horizontal stacked barplot using ggplot. Below are the actual values for three out of 300 sites in my data frame. Here's where I've gotten to so far, using info pulled from these previous questions which I admit I may not have fully understood.
df <- data.frame(id=c("AR001","AR001","AR001","AR001","AR002","AR002","AR002","AR003","AR003","AR003","AR003","AR003"),
landuse=c("agriculture","developed","forest","water","agriculture","developed","forest","agriculture","developed","forest","water","wetlands"),
percent=c(38.77,1.76,59.43,0.03,69.95,0.42,29.63,65.4,3.73,15.92,1.35,13.61))
df
id landuse percent
1 AR001 agriculture 38.77
2 AR001 developed 1.76
3 AR001 forest 59.43
4 AR001 water 0.03
5 AR002 agriculture 69.95
6 AR002 developed 0.42
7 AR002 forest 29.63
8 AR003 agriculture 65.40
9 AR003 developed 3.73
10 AR003 forest 15.92
11 AR003 water 1.35
12 AR003 wetlands 13.61
str(df)
'data.frame': 12 obs. of 3 variables:
$ id : Factor w/ 3 levels "AR001","AR002",..: 1 1 1 1 2 2 2 3 3 3 ...
$ landuse: Factor w/ 5 levels "agriculture",..: 1 2 3 4 1 2 3 1 2 3 ...
$ percent: num 38.77 1.76 59.43 0.03 69.95 ...
df <- transform(df,
landuse.ord = factor(
landuse,
levels=c("agriculture","forest","wetlands","water","developed"),
ordered =TRUE))
cols <- c(agriculture="maroon",forest="forestgreen",
wetlands="gold", water="dodgerblue", developed="darkorchid")
ggplot(df,aes(x = id, y = percent, fill = landuse.ord, order=landuse.ord)) +
geom_bar(position = "stack",stat = "identity", width=1) +
coord_flip() +
scale_fill_manual(values = cols)
which produces this graph.
What I would like to do is to reorder the bars so that they are in descending order by value for the agriculture category - in this example AR002 would be at the top, followed by AR003 then AR001. I tried changing the contents of aes to aes(x = reorder(landuse.ord, percent), but that eliminated the stacking and seemed to have maybe summed the percentages for each land use category:
I would like to have the stacks in order, from left to right: agriculture, forest, wetlands, water, developed. I tried doing that with the transform part of the code, which put it in the correct order in the legend, but not in the plot itself?
Thanks in advance... I have made a ton of progress based on answers to other peoples' questions, but seem to now be stuck at this point!
Update: here is the finished graph for all 326 sites!
Ok based on your comments, I believe this is your solution. Place these lines after cols<-...:
#create df to sort by argiculture's percentage
ag<-filter(df, landuse=="agriculture")
#use the df to sort and order df$id's levels
df$id<-factor(df$id, levels=ag$id[order(ag$percent)], ordered = TRUE)
#sort df, based on ordered ids and ordered landuse
df<-df[order(df$id, df$landuse.ord),]
ggplot(df,aes(x = id, y = percent, fill = landuse.ord, order=landuse.ord)) +
geom_bar(position = "stack",stat = "identity", width=1) +
coord_flip() +
scale_fill_manual(values = cols)
The comments should clarify each of the lines purposes. This will reorder your original data frame, if that is a problem I would create a copy and then operate on the new copy.
Related
I have an existing ggplot with geom_col and some observations from a dataframe. The dataframe looks something like :
over runs wickets
1 12 0
2 8 0
3 9 2
4 3 1
5 6 0
The geom_col represents the runs data column and now I want to represent the wickets column using geom_point in a way that the number of points represents the wickets.
I want my graph to look something like this :
As
As far as I know, we'll need to transform your data to have one row per point. This method will require dplyr version > 1.0 which allows summarize to expand the number of rows.
You can adjust the spacing of the wickets by multiplying seq(wickets), though with your sample data a spacing of 1 unit looks pretty good to me.
library(dplyr)
wicket_data = dd %>%
filter(wickets > 0) %>%
group_by(over) %>%
summarize(wicket_y = runs + seq(wickets))
ggplot(dd, aes(x = over)) +
geom_col(aes(y = runs), fill = "#A6C6FF") +
geom_point(data = wicket_data, aes(y = wicket_y), color = "firebrick4") +
theme_bw()
Using this sample data:
dd = read.table(text = "over runs wickets
1 12 0
2 8 0
3 9 2
4 3 1
5 6 0", header = T)
I am using facet grid to generate neat presentations of my data.
Basically, my data frame has four columns:
idx, density, marker, case.
There are 5 cases, each case corresponds to 5 markers, and each marker corresponds to multiple idx, each idx corresponds to one density.
The data is uploaded here:
data frame link
I tried to use facet_grid to achieve my goal, however, I obtained a really messed up graph:
The x-axis and y-axis are messed up, the codes are:
library(ggplot2)
library(cowplot)
plot.density <-
ggplot(df_densityWindow, aes(x = idx, y = density)) +
geom_col() +
facet_grid(marker ~ case, scales = 'free') +
background_grid(major = 'y', minor = "none") + # add thin horizontal lines
panel_border() # and a border around each panel
plot(plot.density)
EDIT:
I reupload the file, now it should be work:
download file here
All 4 columns have been read as factors. This is an issue from however you loaded the data into R. Take a look at:
df <- readRDS('df.rds')
str(df)
'data.frame': 52565 obs. of 4 variables:
$ idx : Factor w/ 4712 levels "1","10","100",..: 1 1112 2223 3334 3546 3657 3768 3879 3990 2 ...
$ density: Factor w/ 250 levels "1022.22222222222",..: 205 205 204 203 202 201 199 198 197 197 ...
$ marker : Factor w/ 5 levels "CD3","CD4","CD8",..: 1 1 1 1 1 1 1 1 1 1 ...
$ case : Factor w/ 5 levels "Case_1","Case_2",..: 1 1 1 1 1 1 1 1 1 1 ...
Good news is that you can fix it with:
df$idx <- as.integer(as.character(df$idx))
df$density <- as.numeric(as.character(df$density))
Although you should look into how you are loading the data, to avoid future.
As another trick, try the above code without using the as.character calls, and compare the differences.
As already explained by MrGumble, the idx and density variables are of type factor but should be plotted as numeric.
The type.convert() function does the data conversion in one go:
library(ggplot2)
library(cowplot)
ggplot(type.convert(df_densityWindow), aes(x = idx, y = density)) +
geom_col() +
facet_grid(marker ~ case, scales = 'free') +
background_grid(major = 'y', minor = "none") + # add thin horizontal lines
panel_border() # and a border around each panel
I am using the ..count.. transformation in geom_bar and get the warning
position_stack requires non-overlapping x intervals when some of my categories have few counts.
This is best explained using some mock data (my data involves direction and windspeed and I retain names relating to that)
#make data
set.seed(12345)
FF=rweibull(100,1.7,1)*20 #mock speeds
FF[FF>60]=59
dir=sample.int(10,size=100,replace=TRUE) # mock directions
#group into speed classes
FFcut=cut(FF,breaks=seq(0,60,by=20),ordered_result=TRUE,right=FALSE,drop=FALSE)
# stuff into data frame & plot
df=data.frame(dir=dir,grp=FFcut)
ggplot(data=df,aes(x=dir,y=(..count..)/sum(..count..),fill=grp)) + geom_bar()
This works fine, and the resulting plot shows the frequency of directions grouped according to speed. It is of relevance that the velocity class with the fewest counts (here "[40,60)") will have 5 counts.
However more velocity classes leads to a warning. For instance, with
FFcut=cut(FF,breaks=seq(0,60,by=15),ordered_result=TRUE,right=FALSE,drop=FALSE)
the velocity class with the fewest counts (now "[45,60)") will have only 3 counts and ggplot2 will warn that
position_stack requires non-overlapping x intervals
and the plot will show data in this category spread out along the x axis.
It seems that 5 is the minimum size for a group to have for this to work correctly.
I would appreciate knowing if this is a feature or a bug in stat_bin (which geom_bar is using) or if I am simply abusing geom_bar.
Also, any suggestions how to get around this would be appreciated.
Sincerely
This occurs because df$dir is numeric, so the ggplot object assumes a continuous x-axis, and aesthetic parameter group is based on the only known discrete variable (fill = grp).
As a result, when there simply aren't that many dir values in grp = [45,60), ggplot gets confused over how wide each bar should be. This becomes more visually obvious if we split the plot into different facets:
ggplot(data=df,
aes(x=dir,y=(..count..)/sum(..count..),
fill = grp)) +
geom_bar() +
facet_wrap(~ grp)
> for(l in levels(df$grp)) print(sort(unique(df$dir[df$grp == l])))
[1] 1 2 3 4 6 7 8 9 10
[1] 1 2 3 4 5 6 7 8 9 10
[1] 2 3 4 5 7 9 10
[1] 2 4 7
We can also check manually that the minimum difference between sorted df$dir values is 1 for the first three grp values, but 2 for the last one. The default bar width is thus wider.
The following solutions should all achieve the same result:
1. Explicitly specify the same bar width for all groups in geom_bar():
ggplot(data=df,
aes(x=dir,y=(..count..)/sum(..count..),
fill = grp)) +
geom_bar(width = 0.9)
2. Convert dir to a categorical variable before passing it to aes(x = ...):
ggplot(data=df,
aes(x=factor(dir), y=(..count..)/sum(..count..),
fill = grp)) +
geom_bar()
3. Specify that the group parameter should be based on both df$dir & df$grp:
ggplot(data=df,
aes(x=dir,
y=(..count..)/sum(..count..),
group = interaction(dir, grp),
fill = grp)) +
geom_bar()
This doesn't directly solve the issue, because I also don't get what's going on with the overlapping values, but it's a dplyr-powered workaround, and might turn out to be more flexible anyway.
Instead of relying on geom_bar to take the cut factor and give you shares via ..count../sum(..count..), you can easily enough just calculate those shares yourself up front, and then plot your bars. I personally like having this type of control over my data and exactly what I'm plotting.
First, I put dir and FF into a data frame/tbl_df, and cut FF. Then count lets me group the data by dir and grp and count up the number of observations for each combination of those two variables, then calculate the share of each n over the sum of n. I'm using geom_col, which is like geom_bar but when you have a y value in your aes.
library(tidyverse)
set.seed(12345)
FF <- rweibull(100,1.7,1) * 20 #mock speeds
FF[FF > 60] <- 59
dir <- sample.int(10, size = 100, replace = TRUE) # mock directions
shares <- tibble(dir = dir, FF = FF) %>%
mutate(grp = cut(FF, breaks = seq(0, 60, by = 15), ordered_result = T, right = F, drop = F)) %>%
count(dir, grp) %>%
mutate(share = n / sum(n))
shares
#> # A tibble: 29 x 4
#> dir grp n share
#> <int> <ord> <int> <dbl>
#> 1 1 [0,15) 3 0.03
#> 2 1 [15,30) 2 0.02
#> 3 2 [0,15) 4 0.04
#> 4 2 [15,30) 3 0.03
#> 5 2 [30,45) 1 0.01
#> 6 2 [45,60) 1 0.01
#> 7 3 [0,15) 6 0.06
#> 8 3 [15,30) 1 0.01
#> 9 3 [30,45) 2 0.02
#> 10 4 [0,15) 6 0.06
#> # ... with 19 more rows
ggplot(shares, aes(x = dir, y = share, fill = grp)) +
geom_col()
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")
Hi Stack Overflow community,
I have a dataset:
conc branch length stage factor
1 1000 3 573.5 e14 NRG4
2 1000 7 425.5 e14 NRG4
3608 1000 44 5032.0 P10 NRG4
3609 1000 0 0.0 P10 NRG4
FYI
> str(dframe1)
'data.frame': 3940 obs. of 5 variables:
$ conc : Factor w/ 6 levels "0","1","10","100",..: 6 6 6 6 6 6 6 6 6 6 ...
$ branch: int 3 7 5 0 1 0 0 4 1 1 ...
$ length: num 574 426 204 0 481 ...
$ stage : Factor w/ 8 levels "e14","e16","e18",..: 1 1 1 1 1 1 1 1 1 1 ...
$ factor: Factor w/ 2 levels "","NRG4": 2 2 2 2 2 2 2 2 2 2 ...
I would like to create facetted line graphs, plotting the mean +/- standard error of the mean
I have tried experimenting and building a ggplot from others (here and on the web).
I have successfully used scripts that will make bargraphs this way:
errbar.ggplot.facets <- ggplot(dframe1, aes(x = conc, y = length))
### function to calculate the standard error of the mean
se <- function(x) sd(x)/sqrt(length(x))
### function to be applied to each panel/facet
my.fun <- function(x) {
data.frame(ymin = mean(x) - se(x),
ymax = mean(x) + se(x),
y = mean(x))}
g.err.f <- errbar.ggplot.facets +
stat_summary(fun.y = mean, geom = "bar",
fill = clrs.hcl(48)) +
stat_summary(fun.data = my.fun, geom = "linerange") +
facet_wrap(~ stage) +
theme_bw()
print(g.err.f)
Source: http://teachpress.environmentalinformatics-marburg.de/2013/07/creating-publication-quality-graphs-in-r-7/
In fact, I have created facetted line graphs with this script:
`ggplot(data=dframe1, aes(x=conc, y = length, group = stage)) +
geom_line() + facet_wrap(~stage)`
image: postimg.org/image/ebpdc0sb7
However, I used a transformed dataset of only means, SEM in another column, but I don't know how to add them.
Given the complexity (for me) of the bargraphs + error line scripts above, I have not yet been able to integrate/synthesize these into something I need.
In this case, the colour is not important to have.
P.S. I apologise for the long thread (and perhaps the overkill on some details). This is my first online R question, so not sure of correct etiquette. Thank you all in advance for being so helpful!
Darian
In case your dataframe has a column for the mean and the se you could do something like this:
library("dplyr")
library("ggplot2")
# Create a dummydataframe with columns mean and se
df <- mtcars %>%
group_by(gear, cyl) %>%
summarise(mean_mpg = mean(mpg), se_mpg = se(mpg))
ggplot(df, aes(x = gear, y = mean_mpg)) +
geom_bar(stat = "identity") +
geom_errorbar(aes(ymin = mean_mpg - se_mpg, ymax = mean_mpg + se_mpg)) +
facet_wrap(~cyl)