ggplot change geom order in legend [duplicate] - r

This question already has answers here:
Sort legend in ggplot2
(2 answers)
Closed 4 years ago.
I have two stacked area plots with a line plotted on top. In both cases, my plotting order has been this:
Create ggplot
Add stacked area (geom_area); change stacked area colors
Add line (geom_line); change line color
In my first graph, the stacked area colors show up above the Reported Catch line my legend, while in my second graph, the Reported Catch line shows up above the stacked area colors. There appears to be no major difference between the two in terms of R code, so I have no idea why are they different in legend order.
How can I change my first graph's legend to match the second graph's legend, so that the "Reported Catch" line is above the stacked area colors?
Plot 1. Incorrect legend order.
Plot 2. Correct legend order.
Please let me know if you'd like a simplified version of my R code.
The dataset I am using can be downloaded here: Sea Around Us

guides(fill = guide_legend(reverse = TRUE) should work!

Related

ggplot, fill much more visible on graph than legend

I have a graphing question that I feel I should know the answer to, but I can't quite figure it out. I've specified 2 different fill colors & have made a legend of it, but when I generate the graph, the fill colors are either...
way too bright on the graph, but just the right in the legend
just right on the graph, but not even visible in the legend
It looks like this has to do with the 'alpha' value I specify, but I'm not sure how to fix this. Any help is appreciated!
#My graphing code
#graph the average output by machine
ggplot(data=tempdf1)+
#dot plot of individual POD machines
geom_point(aes(x=sample,y=mean_perc_FAM_to_ref,color=POD_machine),width=0.1)+
#line plot of the mean across POD machines
stat_summary(aes(x=sample,y=mean_perc_FAM_to_ref,group=known_conc,color=POD_machine),fun=mean,geom="line")+
#wrap by known conc
facet_wrap(.~known_conc,scales="free")+
#ref box for 10% variation from known trait conc
geom_rect(aes(xmin=p10xmin-1,xmax=p10xmax+1,ymin=p10ymin,ymax=p10ymax,fill="10% Error"),alpha=0.005)+
#ref box for 5% variation from known trait conc
geom_rect(aes(xmin=p5xmin-1,xmax=p5xmax+1,ymin=p5ymin,ymax=p5ymax,fill="5% Error"),alpha=0.005)+
scale_fill_manual(values=c("5% Error"="green","10% Error"="yellow"))+
#labels
labs(x="Sample",y="Measured % of Trait",color="POD Machine",fill="Error Range")+
#clean up background, add gridlines (only to y-axis), add x- and y-axis lines
theme(panel.background=element_blank())+
theme(panel.grid=element_line(color="black"))+
theme(panel.grid.major=element_blank())+
theme(panel.grid.minor=element_blank())+
theme(axis.line=element_line(color="black"))+
#customize x-axis so there is no space between graph and y-axis
scale_x_continuous(expand=c(0,0))+
#customize tick marks in y-axis
scale_y_continuous(labels=scales::percent)
When I specify "alpha=0.005" for geom_rect, this is the graph I get
When I specify "alpha=0.5" for geom_rect, this is the graph I get
Thanks for your help!

Settings y-axis limits when stat = "summary" (binomial data) [duplicate]

This question already has answers here:
geom_bar bars not displaying when specifying ylim
(4 answers)
Closed 8 months ago.
I am trying to create a barplot using ggplot2, with the y axis starting at a value greater than zero.
Lets say I have the means and standard errors for hypothetical dataset about carrot length at three different farms:
carrots<-NULL
carrots$Mean<-c(270,250,240)
carrots$SE<-c(3,4,5)
carrots$Farm<-c("Plains","Hill","Valley")
carrots<-data.frame(carrots)
I create a basic plot:
p<-ggplot(carrots,aes(y=Mean,x=Farm)) +
geom_bar(fill="slateblue") +
geom_errorbar(aes(ymin=Mean-SE,ymax=Mean+SE), width=0)
p
This is nice, but as the scale runs from 0 to it is difficult to see the differences in length. Therefore, I would like to rescale the y axis to something like c(200,300). However, when I try to do this with:
p+scale_y_continuous('Length (mm)', limit=c(200,300))
The bars disappear, although the error bars remain.
My question is: is it possible to plot a barplot with this adjusted axis using ggplot2?
Thank you for any help or suggestions you can offer.
Try this
p + coord_cartesian(ylim=c(200,300))
Setting the limits on the coordinate system performs a visual zoom;
the data is unchanged, and we just view a small portion of the original plot.
If someone is trying to accomplish the same zoom effect for a flipped bar chart, the accepted answer won't work (even though the answer is perfect for the example in the question).
The solution for the flipped bar chart is using the argument ylim of the coord_flip function. I decided to post this answer because my bars were also "disappearing" as in the original question while I was trying to re-scale with other methods, but in my case the chart was a flipped one. This may probably help other people with the same issue.
This is the adapted code, based on the example of the question:
ggplot(carrots,aes(y=Mean,x=Farm)) +
geom_col(fill="slateblue") +
geom_errorbar(aes(ymin=Mean-SE,ymax=Mean+SE), width=0) +
coord_flip(ylim=c(200,300))
Flipped chart example

Density scatter plot with legend

Following-up on a question that has already been answered regarding the scatterplot density (see R Scatter Plot: symbol color represents number of overlapping points), I would like to know if there is a way to add the legend of the scatterplot, let's say for instance to the solution proposed by O'brien?

R bar chart colours for groups of bars

Fairly new to R so sorry if this is a dumb question.
I want to plot a bar chart of a lot of data - maybe 100 bars.
I want to use colours and spacing to highlight the "groups", so I might have the first 10 bars in blue, a small gap, the next 20 in red, a small gap and so on.
I can plot the data fine, but how can I do the colouring and gaps in this way?
This can be done quite easily with ggplot2 as provided in links by #Arun.
With base graphics to set space between bars you can use argument space= (sets space before each bar) and argument col= will change color in function barplot().
Here is a example with 20 bars and space between each 5 bars.
df<-sample(1:10,20,replace=T)
barplot(df,space=c(0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0),
col=rep(c("red","blue","green","yellow"),each=5))
If the number of observations in each group is identical then you can convert vector of values to matrix and then plot it (with argument beside=TRUE). In this case you just need to supply colors but bars will be grouped automatically.
df2<-matrix(df,ncol=4)
barplot(df2,beside=TRUE,col=rep(c("red","blue","green","yellow"),each=5))

Remove "floating" axis labels in facet_wrap plot?

Using facet_wrap in ggplot2 to create a grid, but I have an uneven number of panels so the last row is incomplete. At the bottom of the last, blank panel is the axis ticks and text. Is it possible to shift this axis up (giving the last facet in each column the appearance of having applied free_x)? If not, can I remove it altogether as is seen below?
To clarify with examples, this is what I'm getting:
http://sape.inf.usi.ch/sites/default/files/ggplot2-facet-wrap.png
I desire something seen here (though, ideally with axis labelling on the facet in column 4):
Changing facet label to math formula in ggplot2
Thanks for any ideas or insight!
Using facet_wrap, when I do this in 0.9.1, ggplot hides the x-axes on the columns with blanks, as shown below.
movies$decade <- round(movies$year, -1)
ggplot(movies) + geom_histogram(aes(x=rating)) + facet_wrap(~ decade, ncol=5)

Resources