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
Related
I am drawing a PC plot using ggplots.
I know this question has been answered in some previous posts but I could not still solve my problem.
I have a data set called tab which is the output of PCA
sample.id pop EV1 EV2
HT185_MK8-2.sort.bam HA_27 -0.03796869 0.046369552
HT48_SD1A-37.sort.bam HA_14 0.04208393 0.032961404
HT53_IA1A-10.sort.bam HA_1 -0.02580365 0.005262476
HT260_MK1-4.sort.bam HA_20 -0.06090545 0.005578504
HT170_SD2W-14.sort.bam HA_17 0.01288395 0.012117833
Q093_MK7-13.sort.bam HA_26 0.06310162 0.188558067
I want to add labels on each dot in the plot, theses dots are individuals from several populations. So I want to give them their population ID (pop column in the data set).
I am using something this
ggplot(data=tab,aes(EV1,EV2, label=tab[,2])) + geom_point(aes(color=as.factor(pop))) + ylab("Principal component 2") + xlab("Principal component 1")
But I do not get my desired output.
This is my PC plot!
So could anyone help me to add population label on each dot in the plot!
Thanks
Try geom_text:
geom_text(aes(label=as.character(pop)),hjust=0,vjust=0)
Also consider looking into plotly, or setting a threshold on the labels, because labeling every point will lead to a very crowded plot, and probably very little additional useful information.
This question already has an answer here:
Needle plot in ggplot2 [duplicate]
(1 answer)
Closed 8 years ago.
I am trying to make a plot x,y stick plot (like the link in the bottom of the post). I am attempting to make a Mass spectrum plot (basically a stick plot), is there an easy way of doing this with ggplot2? I know how to make the plot with the plot() function in R, however, I would like to be able to make it with ggplot 2, as I need to do some additional modifications afterwards for which I require ggplot2.
So essentially I want to make a x,y stick plot. I am new to R, so bear with me.
Example of what I want
Try to upload some code and let us know where you are getting stuck. Also, please refer to the documentation or these examples.
That having been said, I believe this is close to what you want:
library(ggplot2)
ggplot(data = mtcars, aes(x = mpg)) +
geom_bar(binwidth = 1, color = 'white')
This question already has answers here:
Order Bars in ggplot2 bar graph
(16 answers)
Closed 8 years ago.
I tried to finde a solution for my problem but I could not. Probably, my problem is easy for some of you. However, I need support. I would be greatful for any help.
I have made a ggplot for two factors: HGU_type and cycle_complexity to show their proportions:
I used:
g2<-ggplot(t,aes(x=HGU_type,fill = cycle_complexity))+ geom_bar(position="fill")
g2
The graph, I get looks as follow:
I want to have increasing order of the bars on the x-axis...first bar with "nod", second with "shake", third with "retr"...
I tried everything and cannot find the solution.
I would be grateful for a hint
As #Japp pointed out, it's always best to include a minimal reproducible example with your question. I created this data set
#sample data
set.seed(18)
t<-data.frame(
HGU_type=sample(c("jerk","nod","pro","retr","shake","tilt","turn"), 50, replace=T, prob=sample(7)),
cycle_complexity=sample(c("multiple", "single"), 50, replace=T)
)
And a plot like your original one is created by
ggplot(t,aes(x=HGU_type,fill = cycle_complexity))+ geom_bar(position="fill")
In order to change the order in which the bars are drawn, you need to change the levels of the factor used for the x-axis. The reorder() function makes it easy to reorder factors based on different properties. Here we will re-order based on the proportion of "multiple" in each group
t$HGU2<-reorder(t$HGU_type, t$cycle_complexity,FUN=function(x) mean(as.numeric(x)))
Then we can plot with
ggplot(t,aes(x=HGU2,fill = cycle_complexity))+ geom_bar(position="fill")
to get
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
can I separately control the x and y axes using ggplot?
I saw an earlier post describing how to do this (can I separately control the x and y axes using ggplot?)-but it doesn´t work in ggplot 0.9.0. Any ideas how I can remove only the y-axis line, and not the x axis line. The axis.line option does not allow any differenatiation between the two axes.
u<-expand.grid(temp=seq(0,100,10),hum=c(20,90),delta=as.factor(seq(0,10,by=5)))
u$model<-exp(u$temp*log(0.88)+u$hum*log(1.01)+as.numeric(u$delta)*log(1.1))
u2<-subset(u,hum==20)
u4<-subset(u,hum==90)
pl<-ggplot()+
geom_line(data=u2,aes(x=u2$temp,y=u2$model,colour=u2$delta,group=u2$delta))+
geom_line(data=u4,aes(x=temp,y=model,colour=delta,group=delta))
pl+theme_bw()+
opts(panel.grid.minor=theme_blank(),
panel.grid.major=theme_blank(),
legend.key=theme_blank(),
panel.border=theme_rect(colour=NA),
axis.line=theme_segment(colour='grey',size=1))
Now - how can I just have the x-axis and not the y-axis line?
The earlier post recommended
grid.remove(gPath("axis_v", "axis.line.segments"), grep=TRUE)
resulting in
Error in removeDLFromGPath(gPath, name, strict, greppath, grepname,
global, : gPath (axis_v::axis.line.segments) not found
//M
Here is a work-around that may help. Set the plotting limits strictly with coord_cartesian() and then add x-axis line manually. It shouldn't be too hard to calculate the y-axis range programmatically.
opts(axis.line=theme_blank()) +
coord_cartesian(ylim=c(-0.05, 3.3)) +
geom_hline(yintercept=-0.05, colour="grey", size=1.5)
Hi I got a data frame weekly.mean.values with the following structure:
week:mean:ci.lower:ci.upper
Where week is a factor; mean, ci.lower and ci.upper are numeric. For each week, there is only one mean, and one ci.lower or ci.upper.
I was trying to plot a shaded area inside of the 95% confidence interval around the mean, with the following code:
ggplot(weekly.mean.values,aes(x=week,y=mean)) +
geom_line() +
geom_ribbon(aes(ymin=ci.lower,ymax=ci.upper))
The plot, however, came out blank (that is only with x-axis and y-axis present, but no lines, or points, let alone shaded areas).
If I removed the geom_ribbon part, I did get a line. I know that this should be a very simple task but I don't know why I couldn't get geom_ribbon to plot what I wanted. Any hint would be truly appreciated.
I realize this thread is super old, but google still find it.
The answer is that you need to set the ymin and ymax to use a part of the data you are using on the y-axis. It you set them to scalar values then the ribbon covers the entire plot from top to bottom.
You can use
ymin=0
ymax=mean
to go from 0 to your y-point or even
ymin=mean-1
ymax=mean+1
to have the ribbon cover a strip encompassing your actual data.
I may be missing something, but the ribbon will be plotted filled with grey20 by default. You are plotting this layer on top of the data so no wonder it obscures it. Also, it is also possible that the limits for the plot axes derived from the data provided to the initial ggplot() call will not be sufficient to contain the confidence interval ribbon. In that case, I would not be surprised to see a grey/blank plot.
To see if this is the problem, try altering your geom_ribbon() line to:
geom_ribbon(aes(ymin=ci.lower,ymax=ci.upper), alpha = 0.5)
which will plot the ribbon with transparency whic should show the data underneath if the problem is what I think it is.
If so, set the x and y limits to the range of the data +/- the confidence interval you wish to plot and swap the order of the layers (i.e. draw the line on top of the ribbon), and use transparency in the ribbon to show the grid through it.
From ggplot's docs for geom_ribbon (2.1.0):
For each continuous x value, geom_interval displays a y interval. geom_area is a special case of geom_ribbon, where the minimum of the range is fixed to 0.
In this case, x values cannot be factors for geom_ribbon. One solution would be to convert week from a factor to a numeric. e.g.
ggplot(weekly.mean.values,aes(x=as.numeric(week),y=mean)) +
geom_line() +
geom_ribbon(aes(ymin=ci.lower,ymax=ci.upper))
geom_line should handle the switch from factor to numeric without incident, although the X axis scale may display differently.