GGplot Error Continuous Scale Command errors - r

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="")

Related

ggplot2: modify legend's elements for two factors in scatterplot {ggplot2}?

I wish my scatter plot displays two factors: by point size and by shades of grey:
a1<-c(seq(1,10,1))
a2<-c(seq(11,20,1))
a3<-c(rep(c(1,2),each = 5))
a4<-c(rep(c(5,10,15,20,25),2))
df<-data.frame(a1,a2,a3,a4)
t1<-theme(
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(size=.4))
ggplot(df, aes(x= a1, y= a2)) +
geom_point(aes(alpha=factor(a3), size = factor(a4))) + t1 + labs(x = "x label", y = "y label") +
theme(legend.background = element_rect())
So far, more or less good.
My questions are:
how to remove the background in my legend? theme(legend.background = element_rect()) for some reason doesn't work...
how to modify both my legends headers? I imagine by this example : http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/
that is should be something like:
scale_shape_discrete(name ="modified A4", breaks=c("1", "2"), labels = c("one","two")) but I can't figure that how to make it work?
I am sure that I am completely misunderstanding the displaying of two variables in scatter plot, but I can't find a way how to correct it?
Thank you !
Based on suggestions of #user20650 and #inscaven and on more google search I hope to understand better how the ggplot is organized and how to produce my plot:
# dummy data
a1<-c(seq(1,10,1))
a2<-c(seq(11,20,1))
a3<-c(rep(c(1,2),each = 5))
a4<-c(rep(c(5,10,15,20,25),2))
# create data frame
df<-data.frame(a1,a2,a3,a4)
# set nice theme
t1<-theme(
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(size=.4))
# create scatter plot
ggplot(df, aes(x= a1, y= a2)) + # create basic plot
geom_point(aes(size = factor(a4), colour = factor(a3))) + # colour has to be inside of aes !! (ASSIGNED = MAPPED)
scale_colour_grey(name = "Set second\nline in title") + # change title of 1st legend, change colours
scale_size_discrete(name = "Name by size") + # change title of 2nd legend, size of point has been already assigned
theme(legend.key = element_blank()) + # delete grey boxes around the legend
labs(x = "x label", y = "y label") + # set labels on x and y axes
t1 # add nice theme
which results in:

ggplot2 script plots axes on one computer, not another

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

Creating a composite plot using ggplot in R

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)

Scatterplots in R ggplot2 package: moving axes and changing font label sizes

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")

ggplot2: how to remove slash from geom_density legend

I'm trying to plot some overlapping density plots in ggplot2. I'm running into a problem where I cannot remove the diagonal slash from the legend. I have tried using scale_fill_manual() and legend.key as well as the hack from R Cookbook, but I cant seem to get it right.
data(iris)
iris=iris
cols=brewer.pal(3,"Set1")
ggplot(iris) +
geom_density(position="identity",aes(x=iris$Sepal.Length,fill=cols[1]),
colour="black",alpha=.5) +
geom_density(position="identity",aes(x=iris$Sepal.Width,fill=cols[2]),
colour="black",alpha=.5)+
theme_bw() +
scale_fill_identity(guide="legend",labels=c("Sepal Width","Sepal Length"))+
xlab("X axis") +
theme(panel.background=element_blank(),
legend.title=element_blank(),
legend.key = element_rect(),
legend.background = element_blank(),
legend.justification=c(1,0),
legend.position=c(.75,.5),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
What can I do to solve this?
Try this:
+ guides(fill = guide_legend(override.aes = list(colour = NULL)))
although that removes the black outline as well...which can be added back in by change the theme to:
legend.key = element_rect(colour = "black")
I completely forgot to add this important note: do not specify aesthetics via x=iris$Sepal.Length using the $ operator! That is not the intended way to use aes() and it will lead to errors and unexpected problems down the road.

Resources