Points not remaining clear over bar when using dodge - r

When I make my bar graph using this code, it becomes unclear which bar the points are supposed to be above. This seems to happen when I add the col function.
Any help would be great!
ggplot(Data_Task1, aes(Type, Percentage_Correct_WND, fill = Condition, col = Animal)) +
geom_bar(stat = "summary", col = "black", position = "dodge") +
geom_point(position = position_dodge(0.9)) +
labs(x = "", y = "% Correct Without No Digs") +
scale_fill_brewer(palette = "Blues") +
scale_colour_manual(values = c("#000000", "#FF9933", "#00FF33", "#FF0000", "#FFFF00", "#FF00FF")) +
theme(
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
axis.line.x = element_line(colour = "black", size = 0.5),
axis.line.y = element_line(colour = "black", size = 0.5)
)
enter image description here

The issue is that ggplot2 does not know the column in your dataset it should use for the dodging when it comes to the point geom. For the bar geom, it's obvious because different bars are drawn with different fill colors at the same x axis value. For your point geom, ggplot2 is dodging based on the color aesthetic. If you want to force grouping or dodging based on a specific column, you should assign that column to the group= aesthetic.
Here's an example using mtcars. I'm forcing continuous factors to be discrete via as.factor() here.
library(ggplot2)
# plot with incorrect dodging
ggplot(mtcars, aes(x=as.factor(carb), y=mpg, fill=as.factor(cyl), color=as.factor(gear))) +
geom_bar(position="dodge", stat="summary", col='black') +
geom_point(position=position_dodge(0.9), size=3) +
theme_classic()
The bars are dodging based on as.factor(cyl), assigned to the fill aesthetic, but the points are dodging based on as.factor(gear), assigned to the color aesthetic. We override the color aesthetic in the geom_bar() command (as OP did) by defining col='black'.
The solution is to force the points to be grouped (and therefore dodged) based on the same column used for the fill aesthetic, so mapping is group=as.factor(cyl).
ggplot(mtcars, aes(x=as.factor(carb), y=mpg, fill=as.factor(cyl), color=as.factor(gear))) +
geom_bar(position="dodge", stat="summary", col='black') +
geom_point(aes(group=as.factor(cyl)), position=position_dodge(0.9), size=3) +
theme_classic()
Applied to OP's case, the dodging should work with this code:
ggplot(Data_Task1, aes(Type, Percentage_Correct_WND, fill = Condition, col = Animal)) +
geom_bar(stat = "summary", col = "black", position = "dodge") +
# adjust group here to Condition (same as fill)
geom_point(aes(group = Condition)), position = position_dodge(0.9)) +
labs(x = "", y = "% Correct Without No Digs") +
scale_fill_brewer(palette = "Blues") +
scale_colour_manual(values = c("#000000", "#FF9933", "#00FF33", "#FF0000", "#FFFF00", "#FF00FF")) +
theme(
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
axis.line.x = element_line(colour = "black", size = 0.5),
axis.line.y = element_line(colour = "black", size = 0.5)
)

Related

Adding a Legend in ggplot2

I have the following code.
Financial_Wealth.lq,Financial_Wealth.uq,Total_Wealth.lq,Total_Wealth.uq,time=seq(0,(sPar.dNN),1))
ggplot(data, aes(x=time)) +
geom_line(aes(y = Human_Capital.mean), color="red", size=1) +
geom_line(aes(y = Financial_Wealth.mean), color="goldenrod3", size=1) +
geom_ribbon(aes(ymin=Financial_Wealth.lq, ymax = Financial_Wealth.uq), alpha=0.4, fill="goldenrod3") +
geom_line(aes(y = Total_Wealth.mean), color="dodgerblue", size=1)+
geom_ribbon(aes(ymin=Total_Wealth.lq, ymax=Total_Wealth.uq), alpha=0.4, fill = "dodgerblue") +
scale_x_continuous(name = 'Age',
breaks=(c(seq(0,(sPar.dNN),4))))+
scale_y_continuous(name = 'Wealth Level',
breaks = seq(0,100,10))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
legend.title = element_text(size=12, face="bold"),
legend.text = element_text(size=12),
axis.title = element_text(size=12),
axis.text = element_text(size=10)) +
coord_cartesian(xlim = c(0,45), ylim = c(0,100), expand = TRUE)+
scale_fill_manual(name="Median",values=c("goldenrod3", "red","dodgerblue"),
labels = c("Financial Wealth", "Human Capital", "Total Wealth"))+
ggtitle('Optimal Wealth Development')
You can interpret each data input as a vector of numbers of equal length. Can someone please tell me why the legend is not appearing? What do I need to do differently! Thanks in advance :) I have attached the image that it is producing so you get an idea of what I am trying to achieve.
In order to add a legend, you need to specify one of the aesthetics within aes(). In this case, take all of your geom_line() calls and place for each one the color= inside of aes(). The value assigned to color= within aes() will be the text of the label in the legend: not the color. To assign color, you need to add scale_color_manual() and set values= a named vector.
See below for the following changes that should solve your problem, although in the absence of your dataset or a reprex, I'm unable to test the function of the new code.
# original code
... +
geom_line(aes(y = Human_Capital.mean), color="red", size=1) +
geom_line(aes(y = Financial_Wealth.mean), color="goldenrod3", size=1) +
geom_line(aes(y = Total_Wealth.mean), color="dodgerblue", size=1)+
# new plot code
... +
geom_line(aes(y = Human_Capital.mean, color="Human Capital Mean"), size=1) +
geom_line(aes(y = Financial_Wealth.mean, color="Financial Wealth Mean"), size=1) +
geom_line(aes(y = Total_Wealth.mean, color="Total Wealth Mean"), size=1) +
scale_color_manual(values=c(
"Human Capital Mean"="red",
"Financial Wealth Mean"="goldenrod3",
"Total Wealth Mean"="dodgerblue"))

ggplot2: increasing space between categorical axis ticks with geom_point

I have a geom_point plot that with a large number of categorical variables, and a size parameter mapped to a continuous variable. When I make the plot, the categorical variables are too close together, and the large points from within each overlap. Is there any way to give a little breathing room to the axis so that this doesn't happen? I'm aware that an alternative solution is simply to use scale_size_area(max_size = 3) to narrow the range of point sizes, but I'd prefer not to do this as it makes it too difficult to tell them apart.
Here's the code:
plot <- ggplot(allcazfull, aes(x = Family, y = ifelse(Percentage==0,NA, Percentage), fill = Treatment, size = ifelse(Number == 0, NA,Number))) +
facet_wrap(~ Pathogen, scales = "free_x") +
geom_point(shape = 21) +
scale_fill_manual(values = alpha(c("#98fb98","#f77e17","#0d5a0d","#8d0707"),.6)) +
theme_bw() +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
aspect.ratio = 4/1,
strip.background = element_rect(fill="white", linetype = "blank"),
strip.text = element_blank()) +
scale_x_discrete(limits = rev(levels(allcazfull$Family))) +
xlab("") +
ylab("") +
guides(fill = FALSE, size = FALSE) +
coord_flip()
plot
And here's the resulting figure:

My grouped Cross bars DON'T dodge, while my Box plots DO

I want my Crossbars to dodge as well, like my boxplots do, in my example it didn't work, any one can explain what i'm doing wrong or fix my code? I used mtcars as an example and included the result as a picture in which my Crossbars DON'T dodge.
library(ggplot2)
mtcars$am = factor(mtcars$am)
mtcars$vs = factor(mtcars$vs)
cleanup = theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"),
legend.key = element_rect(fill = "white"),
text = element_text(size = 10))
p = ggplot(data = mtcars, aes(x = am , y = mpg, colour = vs)) +
geom_boxplot(aes(colour = vs)) +
stat_summary(aes(colour = vs),
fun.data = "mean_cl_normal",
geom = "crossbar",
position = position_dodge(width = 0.90),
width = .2,
col = "red")
p +
cleanup +
xlab("AM") +
ylab("Miles per Gallon") +
scale_colour_manual(name = "VS",
values = c("Light Gray",
"Dark Grey"))
Which gave me this Graph:
The reason is simple: Specifying col = "red" overwrites the aes mapping to color. There is actually only one group for the crossbars and thus nothing to dodge.
You can fix this by mapping to group:
ggplot(mtcars, aes(x = am , y = mpg, colour = vs)) +
#geom_boxplot() +
stat_summary(aes(group = vs),
fun.data = "mean_cl_normal",
geom = "crossbar",
position = position_dodge(width = 0.9),
width = .2,
col = "red")
However, discarding a color scale only for the crossbars obviously doesn't result in a good plot.

ggplot classic theme missing axes [duplicate]

I am trying to draw this following graph using ggplot2 package, but somehow the axis won't show up. the ticks are there, just not the axis line. I have used the theme(axis.line=element_line()) function, but it wouldn't work.
Here is my code:
library(ggplot2)
ggplot(data = soepl_randsub, aes(x = year, y =satisf_org, group = id)) +
geom_point() + geom_line() +ylab("Current Life Satisfaction") +theme_bw() +
theme(plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank() ) +
theme(panel.border= element_blank()) +
theme(axis.line = element_line(color="black", size = "2"))
I am not sure what went wrong. Here is the chart.
The bug was fixed in ggplot2 v2.2.0 There is no longer a need to specify axis lines separately.
I think this is a bug in ggplot2 v2.1.0. (See this bug report and this one.) A workaround is to set the x-axis and y-axis lines separately.
library(ggplot2)
ggplot(data = mpg, aes(x = hwy, y = displ)) +
geom_point() +
theme_bw() +
theme(plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank() )+
theme(panel.border= element_blank())+
theme(axis.line.x = element_line(color="black", size = 2),
axis.line.y = element_line(color="black", size = 2))
You don't need to specify axis-size for X and Y separately. When you are specifying size="2", R is considering value 2 as non-numeric argument. Hence, axis-line parameter is defaulted to 0 size. Use this line of code:
ggplot(data = mpg, aes(x = hwy, y = displ)) + geom_point() +xlab("Date")+ylab("Value of Home")+theme_bw() +theme(plot.background = element_blank(),panel.grid.major = element_blank(),panel.grid.minor = element_blank()) + theme(panel.border= element_blank()) +
theme(axis.line = element_line(color="black", size = 2))
axis_line inherits from line in R, hence specifying size is mandatory for non-default values.

ggplot2, facet wrap, fixed y scale for each row, free scale between rows

I would like to produce a plot using facet_wrap that has a different y scale for each row of the wrap. In other words, with fixed scales on the same row, free scales on different rows, with a fixed x scale. Free scales doesn't give me exactly what I'm looking for, nor does facet_grid. If possible, I'd like to avoid creating 2 separate plots and then pasting them together. I'm looking for a result like the plot below, but with a y scale max of 300 for the first row, and an y scale max of 50 in the second row. Thanks for any help!
Here is my code:
library(ggplot2)
library(reshape)
# set up data frame
dat <- data.frame(jack = c(150,160,170),
surgeon = c(155,265,175),
snapper = c(10,15,12),
grouper = c(5,12,50))
dat$island<-c("Oahu","Hawaii","Maui")
df<-melt(dat)
# plot
ggplot(df, aes(fill=variable, y=value, x=island)) +
geom_bar(width = 0.85, position= position_dodge(width=0.5),stat="identity", colour="black") +
facet_wrap(~variable, scales = "free_y",ncol=2) +
theme_bw() +
theme(strip.text = element_text(size=15, face="bold"))+
theme(legend.position="none")+
theme(panel.grid.major = element_line(colour = "white", size = 0.2))+
theme(panel.grid.minor = element_line(colour = "white", size = 0.5))+
theme(axis.text.x = element_text(angle = 90, hjust =1, vjust =0.5, size=18))+
labs(y = expression(paste("Yearly catch (kg)")))
Drawing on one of the lower ranked answers from the link Eric commented, you can add a layer that blends into the background to enforce the axes.
Here I created a second data frame (df2) that puts a single point at "Hawaii" and the max value you wanted (300 or 50) for the four variable/fish types. By manually setting the color of the geom_point white, it fades into the background.
library(ggplot2)
library(reshape)
# set up data frame
dat <- data.frame(jack = c(150,160,170),
surgeon = c(155,265,175),
snapper = c(10,15,12),
grouper = c(5,12,50))
dat$island<-c("Oahu","Hawaii","Maui")
df<-melt(dat)
#> Using island as id variables
df2 <- data.frame(island = rep("Hawaii",4), variable = c("jack","surgeon","snapper","grouper"),value = c(300,300,50,50))
ggplot(df, aes(fill=variable, y=value, x=island)) +
geom_bar(width = 0.85, position= position_dodge(width=0.5),stat="identity", colour="black") +
geom_point(data = df2, aes(x = island, y = value), colour = "white") +
facet_wrap(~variable, scales = "free_y",ncol=2) +
theme_bw() +
theme(strip.text = element_text(size=15, face="bold"))+
theme(legend.position="none")+
theme(panel.grid.major = element_line(colour = "white", size = 0.2))+
theme(panel.grid.minor = element_line(colour = "white", size = 0.5))+
theme(axis.text.x = element_text(angle = 90, hjust =1, vjust =0.5, size=18))+
labs(y = expression(paste("Yearly catch (kg)")))

Resources