I wrote a ggplot2 script that produces a plot with 3 points and associated error bars. On my computer it works fine, but the same script run on a colleague's computer omits the x and y axes. Any idea why the same ggplot2 code would produce axes on one computer but not another?
I've pasted the code below. for_group_code is a factor with 3 levels. CIlo, CIhi, and y are continuous variables (mean and associated 95% confidence intervals):
Plotnewdat.fg <- ggplot(newdat.fg, aes(x=for_group_code, y=y)) +
geom_point(aes(shape=dum, size=10)) +
scale_shape_manual(values=c(1,0,15)) +
geom_errorbar(aes(ymin=(CIlo), ymax=(CIhi)), size=1, width=0) +
scale_fill_identity()+
scale_x_discrete(labels=newdat.fg$for_group_code)+
xlab("")+
ylab("Density") +
scale_y_continuous(expand=c(0,0), limits=c(0, ymax), breaks=c(0,round((ymax/2), digits=1),ymax)) +
theme(axis.text.x=element_text(size=10, colour="#000000"), axis.text.y=element_text(size=10, colour="#000000"),
axis.title.x=element_text(size=10, colour="#000000"), axis.title.y=element_text(size=10, vjust=1.0),
panel.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"), plot.title=element_text(face="bold", size=10, vjust=0.9),
legend.position="none")
Plotnewdat.fg
Related
I am working on a homework assignment in R Studio and keep getting the Error: Discrete value supplied to continuous scale error. When doing this part: ggplot()+plot1+plot2+plot3 + coord_equal() + scale_fill_gradient( low="#473B31", high="#FFFFFF") I am not sure how to fix this Ive looked for seimilar solutions but cant find any that help me. Here is the full line of commands we are supposed to enter I highlighted where the issue was
# Create choropleth
plot1<- c(geom_polygon(data=LSOA_FF, aes(long, lat, group = group, fill = imd_rank)))
# Create road plot
plot2<-c(geom_path(data=roads_FF,aes(x=long, y=lat, group=group),size=0.1))
# Combine the plots
ggplot()+plot1+plot2+coord_equal()
We can add a further layer for the locations of the schools, and also adjust the color ramp.
# Create school plot
plot3 <- c(geom_point(data=schools, aes(Easting, Northing,colour='school')))
# Create combined plot
**ggplot()+plot1+plot2+plot3 + coord_equal() + scale_fill_gradient( low="#473B31", high="#FFFFFF")**
**#issue here**
It is also possible to control the other elements of the plot using "theme_bw()" which removes many of the visible elements.
#Create a clean plot
ggplot()+plot1+plot2+plot3 +coord_equal() + scale_fill_gradient( low="#473B31", high="#FFFFFF") + theme_bw()
However, the plot is still a little cluttered and we can turn off many of the elements using "theme()"
ggplot()+plot1+plot2+plot3 +coord_equal() + scale_fill_gradient( low="#473B31", high="#FFFFFF") + theme_bw() +
theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.title=element_blank(),
axis.ticks = element_blank(),
legend.key = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank()) + labs(fill = "IMD Rank",colour="")
I want to make a plot (ggplot) with a date x axis, where the x axis is at y=0, but the x labels are at the bottom. It should look more or less like the graph in this picture:
I tried it with hline like this:
ggplot(coe_melt, aes(x=time, y=value, color=score))+
geom_hline(yintercept=0)+
geom_line(size=2)+
scale_color_manual(values=c('blue','magenta','red','green'), breaks=c('Profitability', 'Growth', 'Safety','Payout'))+
theme_bw()+
theme(legend.position = 'bottom')+
theme(axis.ticks.x = element_blank())
I read in several threads that it can be done with scale_x_continuous(), but the problem is that my x axis contains dates and not numbers. When I tried it with scale_x_continous() I got an error (origin not supplied). I tried it with scale_x_date, but I didn't manage to get the result.
With the code above I get the following plot:
In the end I want a horizontal line/axis with ticks at y=0, I want to remove the "lower x axis" and additionally I would like to have "tight" axes (like in the first picture).
My data looks like this:
> head(coe_melt)
time score value
1 1977-07-01 Profitability 0.4737371
2 1978-07-01 Profitability 0.4918117
3 1979-07-01 Profitability 0.4249600
4 1980-07-01 Profitability 0.3847234
5 1981-07-01 Profitability 0.3604534
6 1982-07-01 Profitability 0.4012554
> coe_melt[c(1,40,79,118),]
time score value
1 1977-07-01 Profitability 0.47373711
40 1977-07-01 Growth 0.51024065
79 1977-07-01 Safety 0.02525786
118 1977-07-01 Payout -0.12501210
See my answer below
ggplot(coe_melt, aes(x=time, y=value, color=score))+
geom_hline(yintercept=0)+
geom_line(size=2)+
scale_color_manual(values=c('blue','magenta','red','green'),
breaks=c('Profitability', 'Growth', 'Safety','Payout'))+
theme_bw()+
theme(legend.position = 'bottom')+
theme(axis.ticks.x = element_blank())+
theme(plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank() )+
theme(panel.border= element_blank())+
theme(axis.line.y = element_line(color="black", size = 0.5))+
expand_limits(y=c(-0.4, 0.8))+
scale_y_continuous(breaks=seq(-0.4, 0.8, 0.2))
With a combination of the answer of Al14 and the answer of baptiste from the linked (similar) question provided by Axeman, I managed to get pretty close to the wished result with the following code:
shift_axis <- function(p, y=0){
g <- ggplotGrob(p)
dummy <- data.frame(y=y)
ax <- g[["grobs"]][g$layout$name == "axis-b"][[1]]
p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(y=1, height=sum(ax$height))), ymax=y, ymin=y)+
geom_hline(aes(yintercept=y), data = dummy) +
theme(axis.ticks.x=element_blank())+
theme(axis.line.y = element_line(color='black'), axis.text.x = element_blank(), legend.title=element_blank(),
plot.background = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), panel.border= element_blank())
}
colo2 <- c("#E41A1C", "#984EA3", "#377EB8", "#4DAF4A")
p <- ggplot(coe_melt, aes(x=time, y=value, color=score))+geom_line(size=2)+
scale_color_manual(values=colo2, breaks=c('Profitability', 'Growth', 'Safety','Payout'))+
theme_bw()+theme(legend.position = 'bottom', axis.title.x = element_blank(), axis.title.y = element_blank())+
scale_x_date(limit=as.Date(c('1977-07-01', '2015-07-01')), expand=c(0,0))
shift_axis(p, 0)
For me that's close enough, thanks for your help everybody ;)
Is there a way to use the distance between the ticks in the y-axis as variable within ggplot function?
I want to plot an annotation whose y-coordinate can be "responsive" to the y-axis scale of a graph.
In the example below, I would like var1 to be the distance between successive y-axis ticks as taken from the parameters of the specific graph, and not a user-defined constant.
Data:
EXse2<- data.frame(wk=c(1,2), EX=c(4.457143, 2.580952), se=c(0.4209481,0.5519333))
Code:
var1<- 0.1
labEX<- "\u002A\u002A"
library(ggplot2)
ggplot(EXse2, aes(x=factor(wk), y=EX, group=1))+
geom_errorbar(aes(ymin=EX-se, ymax=EX+se), width=.2, size=1)+
geom_line(size=1)+
geom_point(size=2)+
annotate("text", label=labEX, x=1.5, y=(mean(EXse2$EX[1:2])+var1))+
xlab("period")+
ylab(expression(bar(EX)))+
theme(
panel.background=element_blank(),
panel.border = element_blank(),
panel.grid.minor.x=element_blank(),
panel.grid.major.x=element_blank(),
panel.grid.minor.y = element_line(colour = "#d9d9d9"),
panel.grid.major.y = element_line(colour = "#bfbfbf"),
axis.line = element_line()
)
You can achieve this by creating to plot first, extracting the tick distances with ggplot_build and then add the annotation:
library(ggplot2)
EXse2<- data.frame(wk=c(1,2), EX=c(4.457143, 2.580952), se=c(0.4209481,0.5519333))
labEX<- "\u002A\u002A"
#first, put your plot in p1
p1 <-
ggplot(EXse2, aes(x=factor(wk), y=EX, group=1))+
geom_errorbar(aes(ymin=EX-se, ymax=EX+se), width=.2, size=1)+
geom_line(size=1)+
geom_point(size=2)+
# I HAVE REMOVED THE ANNOTATE HERE
xlab("period")+
ylab(expression(bar(EX)))+
theme(
panel.background=element_blank(),
panel.border = element_blank(),
panel.grid.minor.x=element_blank(),
panel.grid.major.x=element_blank(),
panel.grid.minor.y = element_line(colour = "#d9d9d9"),
panel.grid.major.y = element_line(colour = "#bfbfbf"),
axis.line = element_line()
)
# extract axis limits
yminticks <- ggplot_build(p1)$panel$ranges[[1]]$y.minor_source
# subtract first tick from second
var1 <- yminticks[2] - yminticks[1]
# and now add the annotate and plot
p1 +
annotate("text", label=labEX, x=1.5, y=(mean(EXse2$EX[1:2])+var1))
I am pretty new to R and am trying to create a composite plot using ggplot. I have searched how to do this and have seen I can use the facet function, however, it seems that this is for plotting data which can be split by type e.g. male/female. I have a data frame and I want to plot recovery against concentration, and recovery against equilibrium time on separate plots but as a composite plot. For this I have the following code:
p1 <- ggplot(dat2, aes(x = EqmTime, y = Recovery))
limits <- aes(ymax = Recovery + RecoveryError, ymin=Recovery - RecoveryError)
p1 + geom_point(size = 4) + geom_errorbar(limits, width=4) + geom_smooth(method = "lm", se = FALSE, colour="gray", size=1.5, linetype="dashed") +
labs(x='Equilibrium Time (hrs)', y='Nitrate Recovery (%)') + theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
p2 <- ggplot(dat2, aes(x = StockConc, y = Recovery))
limits <- aes(ymax = Recovery + RecoveryError, ymin=Recovery - RecoveryError)
p2 + geom_point(size = 4) + geom_errorbar(limits, width=0.1) + geom_smooth(method = "lm", se = FALSE, colour="gray", size=1.5, linetype="dashed") +
labs(x='Concentration (g L-1)', y='Nitrate Recovery (%)') + theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
Additionally, I also have a problem that I cannot get the '-1' in the x axis label of plot 2 as a superscript, and am having trouble setting axis limits. When I set, for example, xlim=20-180, the axis doesn't start and finish at these, but makes these the major tick marks.
I would greatly appreciate any help with this! I know some of these issues have been addressed in other posts but I cannot seem to use this advise to sort the issue here.
From your question, I understand that you want to plot both the ggplots in single plot window. You can do this using gridextra package as:
library(gridExtra)
grid.arrange(p1, p2, nrow=2)
I'm trying to replicate the following chart using ggplot2
The one change I'd like to make from that chart though is to give a colour to each point and its label. Here's what I've tried so far:
library(ggplot2)
library(directlabels)
Z <- c("Label1", "Label2", "Label3", "Label4", "Label5", "Label6", "Label7",
"Label8", "Label9", "Label10", "Label11", "Label12", "Label13", "Label14",
"Label15", "Label16", "Label17", "Label18", "Label19", "Label20", "Label21",
"Label22", "Label23", "Label24")
X <- c(10.32582421, 9.772686421, -13.99202201, 3.803952545, 7.775395482,
-11.82234956, -24.27906403, -6.864457678, -24.62853773, 15.3562638,
-6.476057462, 9.576414602, -5.504090215, 29.74512913, 9.046116821,
15.79954557, -39.61679645, -0.90307239, 21.12503086, 15.30221473,
13.40781808, -6.803226537, -4.045907666, -0.134057007)
Y <- c(0.037608141, 0.010581738, 0.117730985, 0.022347258, 0.069347278,
0.026699666, 0.028739498, 0.040611306, 0.036626248, 0.034854158,
0.039310836, 0.03122964, 0.009422296, 0.021935924, 0.050006846,
0.036285691, 0.016796701, 0.057764277, 0.028421772, 0.042726693,
0.037513217, 0.058422072, 0.066859355, 0.078158403)
mychart <- data.frame(Z, X, Y)
q <- ggplot(mychart, aes(X, Y)) + geom_point(aes(colour = Z)) + theme_bw()
direct.label(q)
And I get the following result:
There are three things I'm having trouble figure out:
I'd like to remove the grey quadrant lines.
I'd like to move the axes so that they are centered in the chart, with plots distributed across the 4 quadrants.
I'd like to reduce the label font sizes - I suspect that's why some of them don't end up close to their points.
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))
Use +xlim(min,max) and +ylim(min,max) to set the axis limits for your plot. Then you can use +geom_hline(y=yvalue) and +geom_vline(x=xvalue) to add the horizontal and vertical lines to your plot to designate the four quadrants.
Instead of using +direct.label(q), use +geom_text(aes(label=q,size=sizevalue),where 'sizevalue' is a numeric value that determines the size of the labels (so you can experiment with this).
EDIT: Try this code, which should fix your point labels. (I don't know of a way to move the axis labels up to the lines you drew in, nor a native way to simply move the original axes into the center of your plot. Sorry!):
ggplot(mychart, aes(X, Y)) +
geom_point(aes(colour = Z)) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black")) +
xlim(-40,40) +
ylim(0,0.12) +
geom_hline(y=0.04) +
geom_vline(y=0) +
geom_text(aes(x=X,y=Y+0.003,label=Z,color=Z)) +
theme(legend.position="none")
EDIT 2: Jitter in geom_text
ggplot(mychart, aes(X, Y, colour=Z)) +
geom_point() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black")) +
geom_text(aes(label=Z),
position = position_jitter(width=2, height=0.005)) +
xlim(-40,40) +
ylim(0,0.12) +
geom_hline(y=0.04) +
geom_vline(y=0) +
theme(legend.position="none")