Reorder levels of facet_wrap using ggplot - r

I have an existing dataset with three factors. I would like to plot these three factors using facet_grid() and have them ordered based on how they are ordered in the dataset instead of alphabetical order. Is this possible to do somehow without modifying my data structure?
Here's the data:
https://dl.dropboxusercontent.com/u/22681355/data.csv
data<-read.csv("data.csv", head=T)
ggplot(data, aes(time,a, color="one")) +
geom_line(linetype=1, size=0.3) +
scale_y_continuous(breaks=seq(0,1,0.2)) +
scale_x_continuous(breaks=seq(100,300,50)) +
theme_bw() +
geom_line(aes(time,b)) +
geom_line(aes(time,c)) +
geom_line(aes(time,d))+facet_wrap(~X.1)

This question appears quite too often on SO. You've to get the desired column (by which you're facetting) as a factor with levels in the order you desire, as follows:
data$X.1 <- factor(data$X.1, levels=unique(data$X.1))
Now, plot it and you'll get the facetted plot in the desired order.

Related

ggplot geom_bar shows wrong scale

I'm stuck. I am trying to make a barplot using ggplot:
ggplot(data_ocena, aes(x=grupa, y=ocena, fill=ocena)) +
geom_bar(stat="identity") +
xlab("częstość występowania poszczególnych ocen na kolokwium")
results in:
how to deal with that? variable ocena is factor, group is factor also.

R - order of legend ggplot

I have the following data frame:
Author<-c("University","Office", "School","University","Office", "School","University","Office", "School")
Typ<-c("Text", "Text", "Text","Data", "Data","Data", "List", "List", "List")
Number<-c("3","1","6","4","4","2","8","1","1")
df<-data.frame(Typ,Author,Number)
If I apply:
ggplot(df, aes(x=Author, y=Number, fill=Typ)) +
geom_bar(stat='identity') + coord_flip()
then I get a stacked bar plot where the bars are orders in the order of the date frame, i.e. Text, Data, List, but the legend is in alphabethic order. Is there any (non brute force, ie. by hand) option such that I can rearrange the legend also in the "given" order of the df, i.e. in Text, Data, List?
(just to clarify - I have a bunch of data frames like that which are also bigger in the sense that the vectors "Typ" (which are also different in each data frame) have more entries whose order should not be changed and also displayed in the legend. I wrote a routine which plots all these data frames so I cannot change the legends manually - I am really looking for a routine friendly solution)
You could automatically set your levels according to the order how they appear in your data.frame:
df$Typ <- factor(df$Typ, levels = unique(df$Typ))
ggplot(df, aes(x=Author, y=Number, fill=Typ)) +
geom_bar(stat='identity') + coord_flip()
In this way you change the order of your factor according to the order in df$Typ:

grouping bars in bar-plot without using facets

I want to group the bars in a stacked barplot according to the values in another factor-variable. However, I want to do this without using facets.
my data in long format
I want to group the stacked bars according the afk variable. The normal stacked bar plot can be made with:
ggplot(nl.melt, aes(x=naam, y=perc, fill=stemmen)) +
geom_bar(stat="identity", width=.7) +
scale_x_discrete(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
coord_flip() +
theme_bw()
which gives an alfabetically ordered barplot:
I tried to group them by using x=reorder(naam,afk) in the aes. But that didn't work. Also using group=afk does not have the desired effect.
Any ideas how to do this?
reorder should work but the problem is you're trying to re-order by a factor. You need to be explicit on how you want to use that information. You can either use
nl.melt$naam <- reorder(nl.melt$naam, as.numeric(nl.melt$afk))
or
nl.melt$naam <- reorder(nl.melt$naam, as.character(nl.melt$afk), FUN=min)
depending on whether you want to sort by the existing levels of afk or if you want to sort alphabetically by the levels of afk.
After running that and re-running the ggplot code, i get
An alternative to #MrFlick's approach (based on the answer #CarlosCinelli linked to) is:
ggplot(nl.melt, aes(x=interaction(naam,afk), y=perc, fill=stemmen)) +
geom_bar(stat="identity", width=.7) +
scale_x_discrete(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
coord_flip() +
theme_bw()
which gives:
R tends to see the order of levels as a property of the data rather than a property of the graph. Try reordering the data itself before calling the plotting commands. Try running:
nl.melt$naam <- reorder(nl.melt$naam, nl.melt$afk)
Then run your ggplot code. Or use other ways of reordering your factor levels in naam.

ggplot2 stacked barplots, formatting, and grids

In the data that I am attempting to plot, each sample belongs in one of several groups, that will be plotted on their own grids. I am plotting stacked bar plots for each sample that will be ordered in increasing number of sequences, which is an id attribute of each sample.
Currently, the plot (with some random data) looks like this:
(Since I don't have the required 10 rep for images, I am linking it here)
There are couple things I need to accomplish. And I don't know where to start.
I would like the bars not to be placed at its corresponding nseqs value, rather placed next to each other in ascending nseqs order.
I don't want each grid to have the same scale. Everything needs to fit snugly.
I have tried to set scales and size to for facet_grid to free_x, but this results in an unused argument error. I think this is related to the fact that I have not been able to get the scales library loaded properly (it keeps saying not available).
Code that deals with plotting:
ggfdata <- melt(fdata, id.var=c('group','nseqs','sample'))
p <- ggplot(ggfdata, aes(x=nseqs, y=value, fill = variable)) +
geom_bar(stat='identity') +
facet_grid(~group) +
scale_y_continuous() +
opts(title=paste('Taxonomic Distribution - grouped by',colnames(meta.frame)[i]))
Try this:
update.packages()
## I'm assuming your ggplot2 is out of date because you use opts()
## If the scales library is unavailable, you might need to update R
ggfdata <- melt(fdata, id.var=c('group','nseqs','sample'))
ggfdata$nseqs <- factor(ggfdata$nseqs)
## Making nseqs a factor will stop ggplot from treating it as a numeric,
## which sounds like what you want
p <- ggplot(ggfdata, aes(x=nseqs, y=value, fill = variable)) +
geom_bar(stat='identity') +
facet_wrap(~group, scales="free_x") + ## No need for facet_grid with only one variable
labs(title = paste('Taxonomic Distribution - grouped by',colnames(meta.frame)[i]))

R - Reordering One Factor (for labeling purposes in ggplot) by another

How can I order the levels of a factor in one data.frame column according to the coincident order of levels of another factor?
For example, in the code:
require(RJSONIO)
require(ggplot2)
race.data.json=fromJSON('http://ergast.com/api/f1/2011/constructors/mclaren/results.json?limit=50')
pd=function(rd,df=NULL) {
for (el in rd$MRData$RaceTable$Races)
for (el2 in el$Results){
tmp=data.frame(row.names=NULL,round=as.numeric(el$round),race=el$raceName,num=el2$number,pos=el2$position,driver=el2$Driver['familyName'])
df=rbind(df,tmp)
}
df
}
df=pd(race.data.json)
df$pos=factor(df$pos,levels=c('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','DNF') )
ggplot(df)+geom_point(aes(x=round,y=pos,col=driver))+scale_colour_discrete(name="Driver")
how can I generate a set of x-axis labels using the df$race factor ordered according to the df$round order (numerical order)? That is, if I add +scale_x_discrete(labels=df$race) to the ggplot command, how can I ensure that the x-axis labels follow the order of the original x-axis df$round values?
If your data frame is already sorted, and race is a character, you can cheat a little and do this:
ggplot(df)+geom_point(aes(x=factor(round),y=pos,col=driver)) +
scale_colour_discrete(name="Driver") +
opts(axis.text.x = theme_text(angle = 90)) +
scale_x_discrete(labels = unique(df$race))
Otherwise, relevel and reorder are the way to go, as Chase says.

Resources